为什么初始化程序不能处理返回 list的属性?
找不到这个问题的答案。这一定是显而易见的,但仍然如此。
我尝试在这个简化的示例中使用初始值设定项:
MyNode newNode = new MyNode
{
NodeName = "newNode",
Children.Add(/*smth*/) // mistake is here
};
其中 Children 是此类的属性,它返回一个列表。在这里我遇到了一个错误,类似于“无效的初始化程序成员声明符”。
这里出了什么问题,如何初始化这些属性?预先非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您不能在对象初始值设定项中调用类似的方法 - 您只能设置属性或字段,而不能调用方法。然而,在这种情况下,您可能仍然可以使用对象和集合初始值设定项语法:
请注意,这不会尝试为
Children
分配新值,它会调用Children.Add(...)
,如下所示: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:
Note that this won't try to assign a new value to
Children
, it will callChildren.Add(...)
, like this:这是因为children属性没有初始化
It is because the children property is not initialized
因为您正在执行一个方法,而不是赋值
Because you're executing a method, not assigning a value
字段初始值设定项语法只能用于设置字段和属性,不能用于调用方法。如果
Children
是List
,您也许可以通过这种方式完成它,还包括列表初始值设定项语法:The field initializer syntax can only be used for setting fields and properties, not for calling methods. If
Children
isList<T>
, you might be able to accomplish it this way, by also including the list initializer syntax:以下不是在初始化程序中设置值:
它正在尝试访问字段的成员(也是尚未初始化的成员。)
The following is not setting a value in the initialiser:
It's trying to access a member of a field (a not-yet-initialised one, too.)
初始化器只是初始化属性,而不是其他操作。
您并不是在尝试初始化 Children 列表,而是在尝试向其中添加一些内容。
Children = new List()
正在初始化它。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.