C#记录构造函数参数默认值空IEnumerable

问题描述

我正在转换这个类

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 认初始化为空枚举的方法,因为它必须是编译时常量。我尝试静态初始化只读数组,但同样的问题。

解决方法

由于 IEnumerable<string> 是引用类型,因此唯一可能的默认参数是 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();
}

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

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