2013-05-29 24 views
0
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; 
    } 
} 

我想使用的變量「a」在我CALSS,但我不能獲得通過「移動」它交給我的課我正在使用的構造函數。 我收到的錯誤消息是:錯誤一個字段初始不能引用非靜態字段,方法或屬性

錯誤:字段初始值設定項無法引用非靜態字段,方法或屬性。

我知道這是一個基本的問題,但幫助表示讚賞

class Class1 
    { 


    private int r; 
    private int x; 

    public Construct(int p, int c) 
    { 
     this.r = p; 
     this.x = c; 
    } 

    } 
+0

它在'Class1 class = new Class1(30,a);'行出錯。這條線應該做什麼? – SWeko

+0

你想用什麼課程?並且不要使用關鍵字作爲可變名(它不應該編譯)。 – Serge

+0

我打算用一個寓言曲線做一個球,我正在考慮把'a'作爲時間和我的x座標,並用它來創建一個方程來計算y座標 – Frostbite

回答

3

只是class1初始化移動到一個構造函數:

class Form1 { 
    int a = 0; 

    Class1 obj1; 

    public Form1() { 
     obj1 = new Class1(a); 
    } 
} 
+0

關心詳細說明原因?可能對OP有用。 (或者指出他做錯了什麼) –

+0

我不太清楚限制背後的原因,除了避免一些不直觀的初始化行爲。 – millimoose

+0

一個實例字段不能用於初始化另一個實例字段。 「a」可能在「class」之前未被初始化,反之亦然。 – Steve

1

不能初始化取決於另一個字段的字段類。

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.

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.

所以,在你的代碼,aclass之前,雖然我不認爲編譯器關心是否初始化,在字母順序之前或之後出現。它只是不允許你使用一個實例變量來初始化另一個實例變量。

相關問題