gpt4 book ai didi

c# - 同一属性上的初始化 + 私有(private)集访问器?

转载 作者:行者123 更新时间:2023-12-04 00:14:53 25 4
gpt4 key购买 nike

是否可以在同一个属性上使用公共(public)初始化访问器和私有(private) setter ?
目前我收到错误 CS1007 “已定义属性访问器”。

public record Stuff
{
public int MyProperty { get; init; private set; } // Error

public void SetMyProperty(int value) => MyProperty = value;
}

var stuff = new Stuff
{
MyProperty = 3, // Using the init accessor
};

stuff.SetMyProperty(4); // Using the private setter (indirectly)
我最好的猜测是使用私有(private)成员变量,该变量的属性 getinit访问器(不是自动实现的)和 setter 成员函数。可以更轻松地完成吗?

最佳答案

与指定构造函数来初始化值类似,您可以使用私有(private)支持字段,以便您仍然可以利用 init 逻辑并允许在没有特定构造函数的情况下进行初始化

public record Stuff
{
private int _myProperty;

public int MyProperty { get => _myProperty; init => _myProperty = value; }

public void SetMyProperty(int value) => _myProperty = value;
}

var stuff = new Stuff
{
MyProperty = 3 // Using the init accessor
};

stuff.SetMyProperty(4); // Using the private setter (indirectly)

关于c# - 同一属性上的初始化 + 私有(private)集访问器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64783995/

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