简体   繁体   English

C#Collection Initializer现有集合的语法

[英]C# Collection Initializer Syntax to an existing collection

There's a syntax in C# that I discovered recently that enables you to initialize a read-only collection during initialization: 我最近在C#中发现了一种语法,它允许您在初始化期间初始化只读集合:

class Foo
{
    public List<Bar> Bars { get; } = new List<Bar>();
}

var foo = new Foo
{
    Bars = 
    {
        new Bar()
    }
}

Which is great as it leads to very expressive code. 这很棒,因为它会产生非常富有表现力的代码。 But I have a situation where I already have a collection of Bar , and I want to initialize it using this syntax (even though Bars is readonly ). 但我有一个情况,我已经有一个Bar的集合,我想用这个语法初始化它(即使Bars是readonly )。 Is there a way to do this? 有没有办法做到这一点?

var bar = new List<Bar>();
var foo = new Foo
{
    Bars =  bar // error: Property or indexer Foo.Bar cannot be assigned to -- it is read only
}

I want to initialize it using this syntax (even though Bars is readonly) 我想使用这种语法初始化它(即使Bars是只读的)

You simply cannot. 你根本做不到。

As we are using the initializer syntax and it actually call the setter method aka set of the property and you have a readonly property which can only be set by the class itself and for setting it form outside the class we need to pass it via constructor of Foo while creating it's instance. 因为我们正在使用初始化器语法并且它实际上调用了setter方法又称属性set ,并且你有一个只能由类本身设置的readonly属性,并且为了在类外部设置它,我们需要通过构造函数传递它Foo在创建它的实例时。

UPDATE: 更新:

The first example code actually ends up call to Add method of the List<T> . 第一个示例代码实际上最终调用了List<T> Add方法。 It will compiled to following code: 它将编译为以下代码:

 Foo foo = new Foo();
 foo.Bars.Add(new Bar());

While you can add new items to the Bars but you cannot change it's reference to point to a different object directly using the initializer due to read-only property while it's totally legit to call the member method of List<Bar> on the instance like Remove , Find etc. 虽然可以增加新的项目到Bars ,但你不能改变它的参考点,以一个不同的对象,直接使用由于初始化为只读属性,而这是完全合法的调用的成员方法List<Bar>像实例RemoveFind

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

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