標籤: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#之有參和無參建構函式,擴充方法