[英]Why collection initializer is not working together with expression body property?
I think it's best to show the code right now: 我认为现在最好显示代码:
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);
}
}
Obviously the Main
method should print 1, 2, 3, 4, 5, 6, but it prints 1, 2, 3 only. 显然,
Main
方法应该打印1,2,3,4,5,6,但它只打印1,2,3。 After initialization foo.Ints2.Count
is equals to zero. 初始化后
foo.Ints2.Count
等于零。 Why? 为什么?
It's because of how you have defined the property Int2. 这是因为您已经定义了Int2属性。 While it is indeed a getter, it's is always returning a new list.
虽然它确实是一个吸气剂,但它总是会返回一个新列表。 Int1 is a read only auto property so it's always returning the same list.
Int1是一个只读的自动属性,所以它总是返回相同的列表。 Equivalent compiler magic code removed for class Foo below:
下面为类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>(); } }
}
As you can see, all mututations to Ints2 are lost because the list is always new. 正如您所看到的,Ints2的所有变异都会丢失,因为列表总是新的。
Ints2 => new List<int>();
is short for Ints2 { get { return new List<int>(); } }
是
Ints2 { get { return new List<int>(); } }
Ints2 { get { return new List<int>(); } }
. Ints2 { get { return new List<int>(); } }
。 It returns a new empty list each time the property is read. 每次读取属性时,它都会返回一个新的空列表。 You already have the fix: your first form stores the list in a field.
您已经有了修复:您的第一个表单将列表存储在一个字段中。
每次访问Ints2
属性时,它都会返回新的List<int>
实例。
public ICollection<int> Ints1 { get; } = new List<int>();
This line means that the backing field returned by the property is initialized with new List<int>()
. 此行表示使用
new List<int>()
初始化属性返回的支持字段。
What Collection initializer do is call Add
method for each element, so Ints1
will have 3 elements ( 1
, 2
, 3
). 什么集合初始化要做的就是调用
Add
每个元素的方法,所以Ints1
将有3个元素( 1
, 2
, 3
)。
public ICollection<int> Ints2 => new List<int>();
Expression bodied means that you are defining the body of the getter
, something like this: 表达身体意味着你正在定义
getter
的主体,如下所示:
public ICollection<int> Ints2 => new List<int>();
{
get
{
return new List<int>();
}
}
Each time you call Ints2
an new instance is returned, thats why Count
property returns 0
. 每次调用
Ints2
都会返回一个新实例,这就是Count
属性返回0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.