gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:22:26 26 4
gpt4 key购买 nike

我有下一个代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com