【问题标题】:Make computed property be calculated once in immutable record types使计算属性在不可变记录类型中计算一次
【发布时间】:2023-02-16 14:46:46
【问题描述】:

我正在使用这样的计算属性制作不可变记录类型:

public record Example
{
    public int A { get; init; }
    public int B { get; init; }
    public int C => A * B;
}

知道记录字段设置器只是 initexample.C 的值在 example 对象的生命周期内永远不会改变。

在上面的示例中,C 属性背后的计算非常简单,但对于具有计算密集型属性的类型,缓存可能会影响程序的速度。有没有一种简单的方法可以使该属性只计算一次?它不应该是不可变记录类型的默认值吗?

当然可以放弃计算属性的想法并在构造函数中进行计算:

public record Example
{
    public int A { get; init; }
    public int B { get; init; }
    public int C { get; private init; }
    
    public Example(int A, int B)
    {
        C = A * B;
    }
}

但是没有构造函数有没有办法做到这一点?

【问题讨论】:

  • 您可以将 AB 设为完整属性,其中将计算 CSee more
  • 你为什么不想要一个构造函数?我认为您的第二个代码非常清晰易懂。

标签: c# record computed-field


【解决方案1】:

我经常使用这种模式来延迟初始化昂贵的值,这些值可能会被引用,也可能不会被引用。

public record Example
{
    private int? _C;
    
    public int A { get; init; }
    public int B { get; init; }
    public int C => _C ??= (A * B);
}

【讨论】:

    【解决方案2】:

    我仍然推荐使用构造函数,因为代码的可读性和通用性。另外,如果C的计算过程比较复杂,定义一个private的方法。

    public record Example
    {
        public int A { get; init; }
        public int B { get; init; }
        public int C { get; init; }
    
        public Example(int a, int b)
        {
            A = a;
            B = b;
            C = InitC();
        }
        
        private int InitC()
        {
            return A * B;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 2014-11-04
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多