简体   繁体   English

为什么在结构的构造函数中设置属性不起作用?

[英]Why does setting the property in the constructor of a struct not work?

I have following code which is not allowed (error below), why?我有以下不允许的代码(下面的错误),为什么?

    struct A
    {
        private int b;

        public A(int x)
        {
            B = x;
        }
        public int B
        {
            get { return b; }
            set { b=value; }
        }

    }

I receive the following error:我收到以下错误:

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在将“this”对象的所有字段分配给字段“Test.x”之前,不能使用“this”对象在将控制返回给调用方之前必须完全分配“Test.x”

A struct's variables all have to be definitely assigned before you can use any methods or properties.在您可以使用任何方法或属性之前,必须明确分配结构的变量。 There are two possible fixes here:这里有两种可能的修复方法:

1) You can explicitly call the parameterless constructor: 1)您可以显式调用无参数构造函数:

public A(int x) : this()
{
    B = x;
}

2) You can use the field instead of the property: 2)您可以使用字段而不是属性:

public A(int x)
{
    b = x;
}

Of course the second option only works in your current form - you have to use the first option if you want to change your struct to use an automatic property.当然,第二个选项仅适用于您当前的形式 - 如果您想更改结构以使用自动属性,则必须使用第一个选项。

However, importantly, you now have a mutable struct.然而,重要的是,您现在拥有了一个可变结构。 This is almost always a very bad idea .这几乎总是一个非常糟糕的主意 I would strongly urge you to use something like this instead:强烈建议你改用这样的东西:

struct A
{
    private readonly int b;

    public A(int x)
    {
        b = x;
    }

    public int B { get { return b; } }
}

EDIT: More details of why the original code doesn't work...编辑:有关为什么原始代码不起作用的更多详细信息...

From section 11.3.8 of the C# spec:来自 C# 规范的第 11.3.8 节:

If the struct instance constructor doesn't specify a constructor initializer, the this variable corresponds to an out parameter of the struct type如果 struct 实例构造函数没有指定构造函数初始值设定项,则this变量对应一个 struct 类型的out参数

Now initially that won't be definitely assigned, which means you can't execute any member function (including property setters) until all the firsts of the struct being constructed have been definitely assigned.现在最初不会明确分配,这意味着您不能执行任何成员函数(包括属性设置器),直到正在构造的结构的所有第一个都被明确分配。 The compiler doesn't know or try to take account of the fact that the property setter doesn't try to read from another field.编译器不知道或试图考虑这样一个事实,即属性设置器不尝试从另一个字段读取。 It's all in aid of avoiding reading from fields which haven't been definitely assigned.这一切都是为了避免从尚未明确分配的字段中读取数据。

MSDN “在结构声明中,除非将字段声明为const或静态,否则无法初始化字段。”

Change your constructor to:将您的构造函数更改为:

public A(int x) :
    this()
{
    B = x;
}

As to "why", refer to 11.3.8 Constructors and 5.3 Definite assignment .至于“为什么”,请参考11.3.8 Constructors5.3 Definite assignment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM