2014-01-21 49 views
2

很抱歉的標題的一般性詞語,我真的不明白,我收到了錯誤。錯誤在C#構建結構

因此,我正在關注this tutorial on C#,並且由「內存管理」部分「結構&」決定。

大約在5:30標誌,他開始創造一個Color結構,所以我跟着,線線。一直以來,他的代碼都沒有顯示任何錯誤。

我的錯誤

礦確實,但是。其中4個,更確切地說:

1)Error 1: Backing field for automatically implemented property 'Color.R' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

錯誤2 & 3相同爲1,除了與Color.G & Color.B替換Color.R

最後,錯誤4:

The 'this' object cannot be used before all of its fields are assigned to.

代碼

這裏是我的代碼爲我的顏色結構(再次,我掙扎注意到我的代碼和教程碩士有什麼區別代碼):

public struct Color 
{ 
    public byte R { get; private set; } 
    public byte G { get; private set; } 
    public byte B { get; private set; } 

    public Color(byte red, byte green, byte blue) 
    { 
     R = red; 
     G = green; 
     B = blue; 
    } 

    public static Color Red 
    { 
     get { return new Color(255, 0, 0); } 
    } 

    public static Color Green 
    { 
     get { return new Color(0, 255, 0); } 
    } 

    public static Color Blue 
    { 
     get { return new Color(0, 0, 255); } 
    } 

    public static Color Black 
    { 
     get { return new Color(0, 0, 0); } 
    } 

    public static Color White 
    { 
     get { return new Color(255, 255, 255); } 
    } 
} 

我完全是C#的新手,但有一些PHP的經驗,所以我對於這裏發生的事情有點困惑。思考?

回答

1

Structs真的只能使用默認的構造函數將初步建成。改變你的構造函數調用默認:

public Color(byte red, byte green, byte blue) 
    : this() 
{ 
    this.R = red; 
    this.G = green; 
    this.B = blue; 
} 

通過調用this您使用的是默認的構造函數,然後在那個特定的實例設置專用值。如果這是一個class而不是一個struct你的代碼可以毫無問題地工作。

+1

非常好,謝謝你的幫助。 – ReactingToAngularVues