简体   繁体   English

为什么初始化程序不能处理返回列表的属性<t> ?

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

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.其中 Children 是此类的属性,它返回一个列表。 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!非常感谢!

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:请注意,这不会尝试为Children分配新值,它会调用Children.Add(...) ,如下所示:

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

It is because the children property is not initialized这是因为 children 属性没有初始化

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

因为你正在执行一个方法,而不是赋值

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:如果ChildrenList<T> ,您也许可以通过这种方式完成它,还包括列表初始值设定项语法:

T myT = /* smth */

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

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.)它试图访问一个字段的成员(也是一个尚未初始化的成员。)

Initializers is just to initialize the properties, not other actions. Initializers 只是初始化属性,而不是其他动作。

You are not trying to initialize the Children list, you are trying to add something to it.您不是在尝试初始化 Children 列表,而是在尝试向其中添加一些内容。

Children = new List<smth>() is initializing it. Children = new List<smth>()正在初始化它。

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

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