添加到只读集合在构造函数? [英] Add to a readonly collection in a constructor?

查看:150
本文介绍了添加到只读集合在构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个C#语言结构,让我将项目添加到一个只读集合属性在构造函数?我想要做这样的事情:

Is there a c# language construct that will allow me to add items to a readonly collection property in a constructor? I want to do something like this:

public class Node{
    public IList<Node> Children {get; protected set;}
    public Node(){
        Children = new ObservableList<Node>();
    }
}



......在我的代码某处...

... in my code somewhere...

var node = new Node {Children.Add(new Node())};



(而不是一个很好的例子,但我希望这对面有想法)...

(not a great example, but I hope this gets the idea across)...

更新

确定抱歉,我需要更清晰。我没有写这个节点类,我不能改变它。我问,如果有一个C#语言的概念,让我添加到只读集合在第二片段参数的构造函数,假设节点类是不可更改。

OK sorry I need to be clearer. I didn't write this Node class, and I cannot change it. I am asking if there is a c# language concept that will allow me to add to the readonly collection in the parameterless constructor in the second snippet, assuming the Node class is not changeable.

推荐答案

试试这个。这是绝对有可能增加建设

Try this. It is definitely possible to add elements on construction

var node = new Node
 {
     Children =
    {
        new Node(),
        new Node()
    }
 };

这篇关于添加到只读集合在构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆