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

前端 未结 2 1703
甜味超标
甜味超标 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: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.

提交回复
热议问题