我有以下不允许的代码(下面的错误),为什么?
struct A
{
private int b;
public A(int x)
{
B = x;
}
public int B
{
get { return b; }
set { b=value; }
}
}
我收到以下错误:
The 'this' object cannot be used before all of its fields are assigned to Field 'Test.x' must be fully assigned before control is returned to the caller
最佳答案
在使用任何方法或属性之前,结构的变量都必须明确分配。这里有两个可能的修复方法:
1) 您可以显式调用无参数构造函数:
public A(int x) : this()
{
B = x;
}
2) 可以使用字段代替属性:
public A(int x)
{
b = x;
}
当然,第二个选项仅适用于您当前的形式 - 如果您想更改结构以使用自动属性,您必须使用第一个选项。
但是,重要的是,您现在拥有一个可变结构。这几乎总是一个非常糟糕的主意。我会强烈敦促你改用这样的东西:
struct A
{
private readonly int b;
public A(int x)
{
b = x;
}
public int B { get { return b; } }
}
编辑:有关原始代码为何不起作用的更多详细信息...
来自 C# 规范的第 11.3.8 节:
If the struct instance constructor doesn't specify a constructor initializer, the
this
variable corresponds to anout
parameter of the struct type
现在最初不会明确分配,这意味着您不能执行任何成员函数(包括属性 setter ),直到被构造的结构的所有第一个都被明确分配。编译器不知道或试图考虑属性 setter 不尝试从另一个字段读取的事实。这一切都是为了避免读取未明确分配的字段。
关于c# - 为什么在结构的构造函数中设置属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154005/