【问题标题】:C# records constructor parameter default value empty IEnumerableC#记录构造函数参数默认值空IEnumerable
【发布时间】:2021-05-04 19:34:09
【问题描述】:

我正在转换这个类

public class MyClass
{
    public IEnumerable<string> Strings { get; }

    public MyClass(IEnumerable<string>? strings = null)
    {
        Strings = strings ?? new List<string>();
    }
}

记录。目前我有这个:

public record MyRecord(IEnumerable<string>? strings = null);

但是,我找不到将IEnumerable 默认初始化为空可枚举的方法,因为它必须是编译时间常数。我尝试静态初始化只读数组,但同样的问题。

【问题讨论】:

    标签: c# parameter-passing default record enumerable


    【解决方案1】:

    由于IEnumerable&lt;string&gt; 是一个引用类型,唯一可能的默认参数是null。绝对没有其他东西可以粘在那里。但!您可以在显式声明的“长格式”自动属性的初始化中从主构造函数引用该属性。这将允许您合并分配给属性的值。

    public record MyRecord(IEnumerable<string>? Strings = null)
    {
        public IEnumerable<string> Strings { get; init; } = Strings ?? Enumerable.Empty<string>();
    } 
    

    See SharpLab

    这实际上为您的记录生成了一个构造函数,类似于您最初的构造函数。以下是上述链接为构造函数生成的内容(可空的属性转换回?):

    public MyRecord(IEnumerable<string>? Strings = null)
    {
        <Strings>k__BackingField = Strings ?? Enumerable.Empty<string>();
        base..ctor();
    }
    

    它有点冗长/不如单线那么紧凑,但它是使用record 完成您所要求的唯一方法,并且它仍然比非record 版本短。

    另请注意,如果您查看生成的代码,该属性最终被声明为不可空,而构造函数参数可空。将此与您开始使用的单行版本进行比较,其中生成的参数可以为空以匹配主构造函数声明。在此解决方案中,您可以更改此行为(如果需要)并将长格式属性也显式标记为可为空。

    【讨论】:

      猜你喜欢
      • 2014-07-09
      • 1970-01-01
      • 2012-02-26
      • 2016-03-01
      • 1970-01-01
      • 2016-07-06
      • 2012-06-30
      • 2020-07-23
      • 2014-05-15
      相关资源
      最近更新 更多