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

标签 c# properties struct

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

    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 an out parameter of the struct type

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

关于c# - 为什么在结构的构造函数中设置属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154005/

相关文章:

c# - 在 C# 中创建日期时间

c# - 调用 webservices 时 Prism 可以模块化吗?

c# - 如何在没有对话框的情况下打印 XPS?

ios - 从 UIView 子类访问属性

c++ - 如何将自定义结构传递到 C++(非 CLI)中的 _variant_t?

c - 结构数组替换自身的值

c# - 如何从 xamarin 表单中的绑定(bind)命令调用函数

java - Struts 2 中 Java 类内部的验证

struct - 比较结构数组和字符串中的元素

xml - 我可以在 Spring Boot 应用程序中使用 xml 属性文件而不是 application.properties 吗?