c# - 组合属性 setter "init and private"(C#9)

标签 c# properties repository aggregateroot c#-9.0

我问的是新的 C#9 特性“init property setter”。下面是一个例子:

public class MyClass
{
    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get; init; }
}

我的问题是如何在初始化后更新“Position”的值。我想要这样的东西:

public class MyClass
{
    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get; init + private set; }

    public void MoveMyClass(int newPositionIndex)
    {
        // Some business code...
        Position = newPositionIndex;
    }
}

在我的真实世界项目中,MyClass 的实例由 Entity Framework 初始化。然后我在上面调用一些业务方法。规则是只允许业务方法在属性上设置值,所以我至少需要私有(private) setter 。但是,如果我有私有(private) setter,则 Entity Framework 无法初始化属性。

最佳答案

C#9 中的自动属性似乎没有此功能。

为了解决这个问题,我将 init 与完整的属性样式(而不是自动属性)结合起来。 Maybee C#10 或更高版本将支持这样的访问修饰符。

public class MyClass
{
    private int _position;

    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get => _position; init => _position = value; }

    public void MoveMyClass(int newPositionIndex)
    {
        // Some business code...
        _position = newPositionIndex;
    }
}

关于c# - 组合属性 setter "init and private"(C#9),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66688865/

相关文章:

Java+Reflection : Invoke method on variable access. 可以吗?

javascript - 如何确定原生 JavaScript 对象是否具有属性/方法?

git - 可视化 github 上的 git 仓库

git - 重新创建git标签后出现“tag already exists in the remote"错误

java - IntelliJ/Maven repo 问题

c# - wcf 接口(interface) : why doesn't it 'just' go to the methode but to the whole class

c# - Windsor WCF 集成工具异步

c# - 为什么在 ASP.NET Web API 中找不到我的 POST 操作?

c# - 基类包含字段 'Head1' ,但其类型不兼容

c# - 哪个标识符变量更适合作为参数传递给方法?