c#之有參和無參建構函式,擴充方法

來源:互聯網
上載者:User

標籤:blog   nbsp   ram   stat   code   自身   方法   test   ase   

例如在程式中建立 Parent類和Test類,在Test有三個建構函式,parent類繼承Test類,那麼我們可以在Test類自身中添加 擴充 方法嗎?

答案:是不可以的。因為擴充方法必須是靜態,且靜態方法是不存在建構函式的。

先看一段代碼:

public class Test    {        public Test()        {            Console.WriteLine("這是無參的建構函式");            }        public Test(string name)        {            Console.WriteLine(string.Format("這是有參的建構函式,想知道name:{0}",name));        }        public Test(Test test, int age)        {            Console.WriteLine("這是含有Test類型的函數");        }    }public class Parent:Test    {        public Parent() : base(new Test(), 11) {            Console.WriteLine("調用Test中的有參建構函式");        }    }class Program    {        static void Main(string[] args)        {            Parent parent = new Parent();           //在調用的時候時候,是先調用了Test中的無參建構函式,接著調用了有Test類行的有參建構函式        }    }

還有一個this()的用法:

public class aaa{      public aaa(int v){}      public aaa() :this(11) {}   }

那麼如何?擴充呢?

public static class HasKz    {        public static void getName(this HasKz kz, int age)        {         //報錯,提示靜態類不能作為參數        }   }
//得到的結論,自身類中不能實現擴充方法

//同時擴充方法是在靜態中定義的

例如在parent正確的定義//public static void GetName(this Test t,int name)

 

c#之有參和無參建構函式,擴充方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.