繁体   English   中英

为什么集合初始值设定项不与表达式body属性一起使用?

[英]Why collection initializer is not working together with expression body property?

我认为现在最好显示代码:

class Foo
{
    public ICollection<int> Ints1 { get; } = new List<int>();

    public ICollection<int> Ints2 => new List<int>();
}

class Program
{
    private static void Main(string[] args)
    {
        var foo = new Foo
        {
            Ints1 = { 1, 2, 3 },
            Ints2 = { 4, 5, 6 }
        };

        foreach (var i in foo.Ints1)
            Console.WriteLine(i);

        foreach (var i in foo.Ints2)
            Console.WriteLine(i);
    }
}

显然, Main方法应该打印1,2,3,4,5,6,但它只打印1,2,3。 初始化后foo.Ints2.Count等于零。 为什么?

这是因为您已经定义了Int2属性。 虽然它确实是一个吸气剂,但它总是会返回一个新列表。 Int1是一个只读的自动属性,所以它总是返回相同的列表。 下面为类Foo删除了等效的编译器魔术代码:

class Foo
{
    private readonly ICollection<int> ints1 = new List<int>(); 
    public ICollection<int> Ints1 { get { return this.ints1; } }

    public ICollection<int> Ints2 { get { return new List<int>(); } }
}

正如您所看到的,Ints2的所有变异都会丢失,因为列表总是新的。

Ints2 => new List<int>(); Ints2 { get { return new List<int>(); } } Ints2 { get { return new List<int>(); } } 每次读取属性时,它都会返回一个新的空列表。 您已经有了修复:您的第一个表单将列表存储在一个字段中。

每次访问Ints2属性时,它都会返回新的List<int>实例。

public ICollection<int> Ints1 { get; } = new List<int>();

此行表示使用new List<int>()初始化属性返回的支持字段。

什么集合初始化要做的就是调用Add每个元素的方法,所以Ints1将有3个元素( 123 )。


public ICollection<int> Ints2 => new List<int>();

表达身体意味着你正在定义getter的主体,如下所示:

public ICollection<int> Ints2 => new List<int>();
{
    get 
    {
        return new List<int>();
    }
}

每次调用Ints2都会返回一个新实例,这就是Count属性返回0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM