自动属性和结构
我想知道以下 C# 代码:
struct Structure
{
public Structure(int a, int b)
{
PropertyA = a;
PropertyB = b;
}
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
它在编译时没有出现错误“在分配所有字段之前不能使用‘this’对象”。对于类似的类,它的编译没有任何问题。
可以通过重构以下内容来使其工作:
struct Structure
{
private int _propertyA;
private int _propertyB;
public Structure(int a, int b)
{
_propertyA = a;
_propertyB = b;
}
public int PropertyA
{
get { return _propertyA; }
set { _propertyA = value; }
}
public int PropertyB
{
get { return _propertyB; }
set { _propertyB = value; }
}
}
但是,我认为向 C# 引入自动属性的全部目的是避免编写以后的代码。这是否意味着自动属性与结构无关?
I am wondering about the following C#-code:
struct Structure
{
public Structure(int a, int b)
{
PropertyA = a;
PropertyB = b;
}
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
It is not compiling with an error "The 'this' object cannot be used before all of its fields are assigned to". For the analogous class it is compiling without any problems.
It can be made working by refactoring to the following:
struct Structure
{
private int _propertyA;
private int _propertyB;
public Structure(int a, int b)
{
_propertyA = a;
_propertyB = b;
}
public int PropertyA
{
get { return _propertyA; }
set { _propertyA = value; }
}
public int PropertyB
{
get { return _propertyB; }
set { _propertyB = value; }
}
}
But, I though that the whole point of introducing auto-properties to the C# was to avoid writing later code. Does that mean that auto-properties are not relevant for the structs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C# 6 中,这个就消失了;问题中的代码编译良好。
虽然 Stefan 给出了答案而不是解决了问题,但我必须建议您不要使用可变结构 - 它会咬住您。可变结构是邪恶的。
IMO,这里的“正确”修复很简单:
In C# 6, this simply goes away; the code in the question compiles fine.
While Stefan has the answer than addresses the question, I have to advise you not to use a mutable struct - it will bite you. Mutable structs are evil.
IMO, the "correct" fix here is simply:
您需要首先调用默认构造函数,如下所示:
You need to call the default constructor first, like so:
正如您所看到的,当在构造函数中引用
PropertyA
时,您正在访问this
对象,编译器不会允许这样做,因为您的字段尚未被访问。尚未初始化。为了解决这个问题,您需要找到一种方法来初始化字段。一种方法是您的示例:如果您不使用自动属性,则字段是显式的,您可以初始化它们。
另一种方法是让构造函数调用另一个初始化字段的构造函数。结构总是隐式地有一个无参数构造函数,它将其字段初始化为零,因此请使用:
As you've seen, when referring to
PropertyA
in your constructor, you're accessing thethis
object, which the compiler won't allow because your fields haven't been initialized yet.To get around this, you need to find a way to initialize the fields. One way is your example: If you don't use auto-properties, then the fields are explicit and you can initialize them.
Another way is to have your constructor call another constructor that initializes the fields. Structs always implicitly have a parameterless constructor that initializes its fields to zero, so use that: