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

标签 c#

我有一个 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/

相关文章:

c# - Unity - 通过 XML 的工厂

c# - 将窗口停靠在另一个窗口中

c# - 在没有集合的情况下编写过滤器?

c# - 可空日期时间上的 linq

java - Kotlin 是否提供其集合接口(interface)的任何实现?

c# - 线程间通信不杀线程

c# - 在 Tensorflow.NET 中加载模型的最佳方式是什么

c# - 如何只查看 Resharper 中的公共(public)方法?

c# - VS2015中如何在注释中放置指向其他项目文件的链接

c# - 如何在静态上下文中获取封闭类型的名称?