为什么不初始化与财产归还名单&LT工作; T>? [英] Why doesn't initializer work with properties returning list<t>?

查看:136
本文介绍了为什么不初始化与财产归还名单&LT工作; 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. 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 */ }
};

请注意,这将不尝试新的值赋给孩子,它会调用 Children.Add(...),像这样的:

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;

这篇关于为什么不初始化与财产归还名单&LT工作; T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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