C# constructor chain and extension method
父类构造函数先于子类构造函数执行,也就是说子类构造函数执行期间,父类已经构造出来,那么父类所有的成员都可以访问。
但是最好还是让父类的构造函数自己去处理自己的逻辑,子类去插手,就有点耦合的意思了。
#region extension method static class objectExtension { public static void Object(this Object obj) { Console.WriteLine("Object constructor!!!"); } } #endregion #region constructor chain abstract class abbase { public abbase() { objectExtension.Object(new Object()); Console.WriteLine("abstract base class!!!"); } } class overrides :abbase { public string NotVirtualFunc() { return "parent not virtual"; } public virtual string VirtualFunc(){return "virtual";} public overrides() { Console.WriteLine("parent constructor!!!"); } } class SubClass : overrides { public SubClass() { Console.WriteLine("sub constructor!!!"); } public override string VirtualFunc() { return base.VirtualFunc(); } public new string NotVirtualFunc() { return "child not virtual"; } } #endregion
static void Main(string[] args) { SubClass child = new SubClass(); Console.WriteLine(child.NotVirtualFunc()); Console.ReadLine(); }