Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么不是';我的基类中的静态构造函数调用了吗?_C#_Static Constructor - Fatal编程技术网

C# 为什么不是';我的基类中的静态构造函数调用了吗?

C# 为什么不是';我的基类中的静态构造函数调用了吗?,c#,static-constructor,C#,Static Constructor,假设我有两门课: public abstract class Foo { static Foo() { print("4"); } } public class Bar : Foo { static Bar() { print("2"); } static void DoSomething() { /*...*/ } } 我希望在调用Bar.DoSomething()(假

假设我有两门课:

public abstract class Foo
{
    static Foo()
    {
        print("4");
    }
}

public class Bar : Foo
{
    static Bar()
    {
        print("2");
    }

    static void DoSomething()
    {
        /*...*/
    }
}
我希望在调用
Bar.DoSomething()
(假设这是我第一次访问Bar类)之后,事件的顺序是:

  • Foo的静态构造函数(同样,假设第一次访问)>print
    4
  • 条形图的静态构造函数>打印
    2
  • 执行
    DoSomething
  • 在底线处,我希望打印
    42

    测试后,似乎只打印了
    2


    你能解释一下这种行为吗?

    基类静态构造函数没有被调用的原因是,我们还没有访问基类的任何静态成员,也没有访问派生类的实例

    根据文档,这些是调用静态构造函数的时间

    它在创建第一个实例或任何其他实例之前自动调用 静态成员被引用

    在下面的代码中,当我们调用
    DoSomething
    时,将调用基类构造函数

       public abstract class Foo
        {
            static Foo()
            {
                Console.Write("4");
                j = 5;
            }
    
            protected static int j;
    
            public static void DoNothing()
            {
    
            }
        }
    
        public class Bar : Foo
        {
            static Bar()
            {
                Console.Write("2");
            }
    
            public static void DoSomething()
            {
                Console.Write(j);
            }
        }
    

    该规范规定:

    类的静态构造函数在给定的应用程序域中最多执行一次。静态构造函数的执行由应用程序域中发生的以下第一个事件触发:

  • 将创建该类的一个实例
  • 将引用该类的任何静态成员
  • 因为您没有引用基类的任何成员,所以没有超出构造函数

    试试这个:

    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()
        {
            /*...*/
        }
    }
    
    有关更多信息:


    请参见自动调用基类的默认构造函数。如果我设计了一种语言,我会考虑调用构造函数,就像创建一个类的实例一样。这不是构造函数的作用吗?