c# - 无法分配结构中自动实现的属性

标签 c# .net constructor automatic-properties

我有下一个代码:

struct T 
{
    public T(int u) 
    { 
        this.U = 10; //Errors are here
    }

    public int U { get; private set;  }
}

C# 编译器在声明的行中给我一对错误: 1) 自动实现的属性“TestConsoleApp.Program.T.U”的支持字段必须在控制返回给调用者之前完全分配。考虑从构造函数初始值设定项调用默认构造函数。 2) 'this' 对象在其所有字段都分配给之前不能使用

我做错了什么?帮助我理解。

最佳答案

来自 C# 规范:

10.7.3 Automatically implemented properties

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.

[Deleted]

Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type.

[Deleted]

This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor.

所以你需要这个:

struct T 
{
    public T(int u)
        : this()
    { 
        this.U = u;
    }

    public int U { get; private set; }
}

关于c# - 无法分配结构中自动实现的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670780/

相关文章:

c# - 您应该在哪里对验证进行单元测试?

jquery - 跨 2 个帧显示一个 DIV

c# - TranslateTransform 移动元素超出预期

constructor - Prolog 中的多个构造函数

c++ - 分配给构造函数? (像一个元组层)

c# - 使用 new 的静态变量初始化会产生代码风险

c# - 有没有办法检查模拟是否已为成员设置?

c# - 在 DocumentDB 中保存和读取 DateTimeOffset

c# - 是否可以隐藏(而不是删除)PivotItem?

c# - 网络 API : Configure JSON serializer settings on action or controller level