为什么在结构的构造函数中设置属性不起作用? [英] Why does setting the property in the constructor of a struct not work?

查看:84
本文介绍了为什么在结构的构造函数中设置属性不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下不允许的代码(错误如下),为什么?

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; }
        }

    }

我收到以下错误:

在分配所有字段之前不能使用this"对象在返回控制之前必须完全分配到字段Test.x"给来电者

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

推荐答案

在使用任何方法或属性之前,必须明确分配结构的变量.这里有两个可能的修复:

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) 您可以显式调用无参数构造函数:

1) You can explicitly call the parameterless constructor:

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

2) 您可以使用字段代替属性:

2) You can use the field instead of the property:

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; } }
}

有关原始代码为何不起作用的更多详细信息...

More details of why the original code doesn't work...

来自 C# 规范的第 11.3.8 节:

From section 11.3.8 of the C# spec:

如果struct实例构造函数没有指定构造函数初始值设定项,则this变量对应一个struct类型的out参数

If the struct instance constructor doesn't specify a constructor initializer, the this variable corresponds to an out parameter of the struct type

现在最初不会明确分配,这意味着您不能执行任何成员函数(包括属性设置器),直到正在构造的结构的所有第一个都被明确分配.编译器不知道或试图考虑这样一个事实,即属性设置器不尝试从另一个字段读取.这一切都是为了避免读取未明确分配的字段.

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.

这篇关于为什么在结构的构造函数中设置属性不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆