c# – 为什么不调用我的基类的静态构造函数?
参见英文答案 >
What’s the best way to ensure a base class’s static constructor is called?6个
可以说我有两节课: public abstract class Foo { static Foo() { print("4"); } } public class Bar : Foo { static Bar() { print("2"); } static void DoSomething() { /*...*/ } } 我预计在调用Bar.DoSomething()之后(假设这是我第一次访问Bar类),事件的顺序将是: > Foo的静态构造函数(再次,假设首次访问)>打印4 在底线我预计会打印42张. 你能解释一下这种行为吗? 解决方法
规范说明:
因为您没有引用基类的任何成员,所以构造函数不会被驱逐. 试试这个: public abstract class Foo { static Foo() { Console.Write("4"); } protected internal static void Baz() { // I don't do anything but am called in inherited classes' // constructors to call the Foo constructor } } public class Bar : Foo { static Bar() { Foo.Baz(); Console.Write("2"); } public static void DoSomething() { /*...*/ } } 欲获得更多信息: > C# in Depth – Jon Skeet: C# and beforefieldinit (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |