Why doesn't initializer work with properties returning list<t>?

淺唱寂寞╮ 提交于 2019-12-06 23:52:19

问题


Couldn't find an answer to this question. It must be obvious, but still.

I try to use initializer in this simplified example:

    MyNode newNode = new MyNode 
    {
        NodeName = "newNode",
        Children.Add(/*smth*/) // mistake is here
    };

where Children is a property for this class, which returns a list. And here I come across a mistake, which goes like 'Invalid initializer member declarator'.

What is wrong here, and how do you initialize such properties? Thanks a lot in advance!


回答1:


You can't call methods like that in object initializers - you can only set properties or fields, rather than call methods. However in this case you probably can still use object and collection initializer syntax:

MyNode newNode = new MyNode
{
    NodeName = "newNode",
    Children = { /* values */ }
};

Note that this won't try to assign a new value to Children, it will call Children.Add(...), like this:

var tmp = new MyNode();
tmp.NodeName = "newNode":
tmp.Children.Add(value1);
tmp.Children.Add(value2);
...
MyNode newNode = tmp;



回答2:


It is because the children property is not initialized

MyNode newNode = new MyNode 
    {
        NodeName = "newNode",
        Children = new List<T> (/*smth*/)
    };



回答3:


Because you're executing a method, not assigning a value




回答4:


The field initializer syntax can only be used for setting fields and properties, not for calling methods. If Children is List<T>, you might be able to accomplish it this way, by also including the list initializer syntax:

T myT = /* smth */

MyNode newNode = new MyNode 
{
    NodeName = "newNode",
    Children = new List<T> { myT }
};



回答5:


The following is not setting a value in the initialiser:

Children.Add(/*smth*/) // mistake is here

It's trying to access a member of a field (a not-yet-initialised one, too.)




回答6:


Initializers is just to initialize the properties, not other actions.

You are not trying to initialize the Children list, you are trying to add something to it.

Children = new List<smth>() is initializing it.



来源:https://stackoverflow.com/questions/6385803/why-doesnt-initializer-work-with-properties-returning-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!