gpt4 book ai didi

c# - 内联列表如何覆盖没有 setter 的属性?

转载 作者:太空狗 更新时间:2023-10-29 22:22:13 24 4
gpt4 key购买 nike

我有一个 Item 类,它有一个不包含 setter 的可公开访问的成员 NoSetter。该对象确实明确声明了一个 get,它检索一个私有(private)的只读 List 对象。

class Item
{
private readonly List<string> emptyString;

public Item()
{
this.emptyString = new List<string>();
}

public List<string> NoSetter
{
get { return this.emptyString; }
}
}

创建此对象时,不能将 NoSetter 设置为列表,无论何时尝试,编译器都会失败。

List<string> goldenString = new List<string>();
goldenString.Add("Nope");
Item item = new Item()
{
NoSetter = goldenString
// or NoSetter = new List<string>();
};

但是,如果您以内联方式创建列表,则可以设置 NoSetter。

Item item = new Item()
{
NoSetter = { "But this still works" }
};

// Outputs: "But this still works"
Console.WriteLine(item.NoSetter.First<string>());

我希望 NoSetter.Get 方法应该返回只读列表 emptyString ,而是返回内联的 NoSetter 对象。在 .net 中是什么原因造成的?是否符合预期?

最佳答案

你的第二段代码不是设置一个新的List<string> ,它只是为其添加该值。

Item item = new Item()
{
NoSetter = { "But this still works" }
};

相当于:

Item item = new Item();
item.NoSetter.Add("But this still works");

{...}应用于集合时的语法称为 Collection Initializer .引用文档(强调我的):

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

关于c# - 内联列表如何覆盖没有 setter 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30781566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com