问题
public partial class Form1 : Form
{
Class1 class = new Class1(30,a);
public Form1()
{
InitializeComponent();
}
public int a = 0;
private void Timer1_Tick(object sender, EventArgs e)
{
a += 1;
}
}
I want to use the variable 'a' in my calss but i cant get "move" it over to my class via the constructor i'm using. The error message i recive is :
Error: A field initializer cannot reference the non-static field, method, or property.
I know it's a basic problem but help is appreciated
class Class1
{
private int r;
private int x;
public Construct(int p, int c)
{
this.r = p;
this.x = c;
}
}
回答1:
Just move the initialization of class1 into a constructor:
class Form1 {
int a = 0;
Class1 obj1;
public Form1() {
obj1 = new Class1(a);
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/16817794/error1a-field-initializer-cannot-reference-the-non-static-field-method-or-pr