Error 1 A field initializer cannot reference the non-static field, method, or property

前端 未结 2 1704
甜味超标
甜味超标 2021-01-26 17:14
 public partial class Form1 : Form
  {
    Class1 class = new Class1(30,a);

    public Form1()
    {

        InitializeComponent();
    }

     public int a = 0;


            


        
相关标签:
2条回答
  • 2021-01-26 17:29

    Just move the initialization of class1 into a constructor:

    class Form1 {
        int a = 0;
    
        Class1 obj1;
    
        public Form1() {
            obj1 = new Class1(a);
        }
    }
    
    0 讨论(0)
  • 2021-01-26 17:51

    You cannot initialize a field that depends on another field of the class.

    From the C# Language Specification 10.5.5:

    Field declarations may include variable-initializers. For static fields, variable initializers correspond to assignment statements that are executed during class initialization. For instance fields, variable initializers correspond to assignment statements that are executed when an instance of the class is created.

    and

    The default value initialization described in §10.5.4 occurs for all fields, including fields that have variable initializers. Thus, when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order.

    So, in your code, a isn't initialized before class, although I don't think the compiler cares whether is comes before or after alphabetically. It just doesn't allow you to use one instance variable to initialize another.

    0 讨论(0)
提交回复
热议问题