2011-10-11 70 views
5

我定義我的結構是這樣的:有什麼不對這種結構類型的定義

struct Test 
{ 
    private string assayName; 
    public string AssayName { get; set; } 

    private string oldUnitName; 
    public string OldUnitName { get; set; } 

    private string newUnitName; 
    public string NewUnitName { get; set; } 

    public Test(string name, string oldValue, string newValue) 
    { 
     assayName = name; 
     oldUnitName = oldValue; 
     newUnitName = newValue; 
    } 

} 

,但它給了我下面的錯誤:

"Error 13 Backing field for automatically implemented property 'EnterResults.frmApplication.Test.NewUnitName' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer."

+2

對於初學者:編譯器不會假定'assayName'是支持字段對於'AssayName' ... –

+0

您的屬性不訪問或變更支持字段。 – canon

+1

在附註上,您可能想要使用'class',而不是'struct'。 –

回答

6

嘛,有兩個問題真的:

1.您使用自動屬性,但隨後也提供領域,存在之間沒有佈線二。

2.當你使用自動屬性時,因爲這是一個結構體,所以它們必須先被初始化。您可以通過調用默認構造函數來完成此操作。因此,修訂版本將是:

struct Test 
{ 
    public Test(string name, string oldValue, string newValue) 
     : this() 
    { 
     AssayName = name; 
     OldUnitName = oldValue; 
     NewUnitName = newValue; 
    } 

    public string AssayName { get; private set; } 
    public string OldUnitValue { get; private set; } 
    public string NewUnitValue { get; private set; } 
} 
+0

正確。謝謝 – Bohn

6

你實際上並沒有做任何事情與屬性。試試這個:

struct Test 
{ 
    public string AssayName { get; set; } 
    public string OldUnitName { get; set; } 
    public string NewUnitName { get; set; } 

    public Test(string name, string oldValue, string newValue) : this() 
    { 
     AssayName = name; 
     OldUnitName = oldValue; 
     NewUnitName = newValue; 
    } 
} 

我認爲這與結構初始化有關。注意到我添加的默認構造函數的調用似乎讓它開心:)

「似乎讓它開心」 - 這是多麼愚蠢。我探討了與結構如何初始化有關的真正答案。調用默認的構造函數確保字段在使用結構之前被初始化。

3

您可以刪除private字段assayName,oldUnitNamenewUnitName。然後,你指的是自動實現的屬性在構造函數:

public Test(string name, string oldValue, string newValue) 
{ 
    AssayName = name; 
    OldUnitName = oldValue; 
    NewUnitName = newValue; 
} 
2

你也可以調用默認的構造函數:

public Test(string name, string oldValue, string newValue) : this() 
{ 
    assayName = name; 
    oldUnitName = oldValue; 
    newUnitName = newValue; 
} 

here

+0

請注意,我沒有假設你的公共和私人變量是相關的(見編碼大猩猩的答案) – KevinDTimm