简体   繁体   English

c#静态构造函数问题

[英]c# static constructor problem

The following code does not call the class static constructor. 以下代码不会调用类静态构造函数。 Is this a bug or feature? 这是一个错误或功能吗?

class Test
{
    static Test
    {
       //do stuff
    }
    public static AnotherClass ClassInstance { get; set; }
}

class Program
{
    public static void Main()
    {
        var x = Test.ClassInstance;
    }
}

I don't have a compiler right now, but this is what happened to me today. 我现在没有编译器,但这就是我今天发生的事情。 The static constructor is never called, but it is called when ClassInstance is a field instead. 永远不会调用静态构造函数,但是当ClassInstance是字段时调用它。

EDIT: I understand that static constructor is called when first instance is created or a field is accessed. 编辑:我知道在创建第一个实例或访问字段时会调用静态构造函数。 Isn't there a field behind the automatic implemented property? 自动实施的属性背后是否有一个字段?

I am looking for some explanation on why the property does not trigger static constructor when property is implemented as two functions and one field. 我正在寻找一些解释,当属性实现为两个函数和一个字段时,属性为什么不触发静态构造函数。 It is just very unlogical to me and that is why I thought it could be a bug. 这对我来说非常不合逻辑,这就是为什么我认为这可能是一个错误。

Static constructors invoked the first time an instance of a class are created or when a static member is referenced. 静态构造函数在第一次创建类的实例或引用静态成员时调用。 So the first time your create an instance of Test or when the ClassInstance property is referenced is when your static constructor will be called. 因此,第一次创建Test实例或引用ClassInstance属性时,将调用静态构造函数。

Would you like to know more? 你想知道更多吗? - http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx - http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx

Static constructor is called when any static member is accessed or instance is created 在访问任何静态成员或创建实例时,将调用静态构造函数

class Program
{
    static void Main(string[] args)
    {
        A.SomeField = new B();
    }
}

class A
{
    static A()
    {
        Console.WriteLine("Static A");
    }

    public static B SomeField { get; set; }
}

class B
{
    static B()
    {
        Console.WriteLine("Static B");
    }
}

Result: 结果:

Static B
Static A

As you see - there is no "Static B" in the result 如您所见 - 结果中没有“静态B”

I verified the same behaviour, but if you change the code like this: 我验证了相同的行为,但如果您更改这样的代码:

class AnotherClass {}

class Test
{
    static Test()
    {
        Console.WriteLine("Hello, world!");
    }

    public static AnotherClass ClassInstance { get { return new AnotherClass(); } }

}

class Program
{
    public static void Main()
    {
        var x = Test.ClassInstance;
    }
}

it writes "Hello, world!"... 它写道:“你好,世界!”......

the static constructor is called automatically before the first instance is created or any static members are referenced. 在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数。

more information from Msdn. 来自Msdn的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM