为什么不能在结构体内初始化非静态字段?

Asa*_*sad 20 .net c# struct field

考虑这个代码块:

struct Animal
{
    public string name = ""; // Error
    public static int weight = 20; // OK

    // initialize the non-static field here
    public void FuncToInitializeName()
    {
        name = ""; // Now correct
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 为什么我们可以初始化static结构中的non-static字段而不是字段?
  • 为什么我们必须non-static在方法体中初始化?

Adr*_*der 7

看看为什么不能使用默认构造函数的值类型?

  • 虽然在IL级别他们可以:http://msmvps.com/blogs/jon_skeet/archive/2008/12/10/value-types-and-parameterless-constructors.aspx (2认同)