很抱歉标题的一般性,我真的不明白我收到的错误。
所以我关注this tutorial on C#,我接受“结构与记忆管理”一节。
在5:30左右,他开始创建一个Color
结构,所以我跟着,一行一行。一直以来,他的代码都没有显示任何错误。
我的错误
然而,我的确如此。其中四个,确切地说: 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.R
替换为Color.G
& Color.B
。
最后,错误4:
The 'this' object cannot be used before all of its fields are assigned to.
代码
这是我的Color结构的代码(同样,我很难注意到我的代码和教程主代码之间的差异):
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经验,所以我对这里究竟发生了什么感到困惑。想法?
答案 0 :(得分:1)
Structs
只能真正使用最初构建的默认构造函数。更改构造函数以调用默认值:
public Color(byte red, byte green, byte blue)
: this()
{
this.R = red;
this.G = green;
this.B = blue;
}
通过调用this
,您正在使用默认构造函数,然后在该特定实例上设置私有值。如果这是一个class
而不是struct
,那么您的代码可以正常运行。