例如在程序中創建 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)