具有自动属性的集合初始值设定项
有没有办法在使用自动属性的同时使用集合初始值设定项?
// Uses collection initializer but not automatic properties
private List<int> _numbers = new List<int>();
public List<int> Numbers
{
get { return _numbers; }
set { _numbers = value; }
}
// Uses automatic properties but not collection initializer
public List<int> Numbers { get; set; }
// Is there some way to do something like this??
public List<int> Numbers { get; set; } = new List<int>();
Is there a way to use a collection initializer when also using automatic properties?
// Uses collection initializer but not automatic properties
private List<int> _numbers = new List<int>();
public List<int> Numbers
{
get { return _numbers; }
set { _numbers = value; }
}
// Uses automatic properties but not collection initializer
public List<int> Numbers { get; set; }
// Is there some way to do something like this??
public List<int> Numbers { get; set; } = new List<int>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,基本上。您必须在构造函数中初始化集合。老实说,无论如何,可设置的集合都不是一个好主意。我实际上会使用(更改您的第一个版本,删除
set
):或者如果我想推迟构建直到第一次访问:
No, basically. You would have to initialize the collection in the constructor. To be honest, a settable collection is rarely a good idea anyway; I would actually use just (changing your first version, removing the
set
):or if I want to defer construction until the first access:
不行。您必须在显式定义的构造函数中进行初始化,这里没有可应用的字段初始化技巧。
此外,这与集合初始化器无关。您也无法
在构造函数之外进行初始化。
No. You have to initialize in an explicitly-defined constructor, there are no field-initialization tricks to apply here.
Also, this has nothing to do with collection intializers. You also can't initialize
outside of a constructor.
显然你的声音被听到了。
我刚刚偶然发现它第一次在新的代码库中使用。
https:// learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
apparently your voice was heard.
I just stumbled across this being used for the first time in a new codebase.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties