代码之家  ›  专栏  ›  技术社区  ›  Asad

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

  •  20
  • Asad  · 技术社区  · 15 年前

    考虑此代码块:

    struct Animal
    {
        public string name = ""; // Error
        public static int weight = 20; // OK
    
        // initialize the non-static field here
        public void FuncToInitializeName()
        {
            name = ""; // Now correct
        }
    }
    
    • 为什么我们可以初始化 static 结构内的字段,但不是 non-static 字段?
    • 为什么要初始化 非静态 在方法体中?
    4 回复  |  直到 12 年前
        2
  •  1
  •   supercat    13 年前

        3
  •  0
  •   Mehrdad Afshari    15 年前

        4
  •  -1
  •   Daniel Earwicker    15 年前

    struct Animal
    {
        public string name = ""; 
        public static int weight = 20; 
    
        public Animal(bool someArg) : this() { }
    }
    

    this()

    name new Animal(someBool)

    new Animal()