[英]How do I create an auto-implemented list property in a class in C#?
To begin with I made a class with fields like this: 首先,我制作了一个具有如下字段的类:
class Person
{
public string name;
public List<Thing> things = new List<Thing>();
public Person(string name)
{
this.name = name;
}
}
and directly changed the field things
outside the class, but later found out that this is not the best practice as the fields of class should be private and accessed using public properties instead. 并直接更改了类之外的字段things
,但后来发现这不是最佳实践,因为类的字段应为私有字段,而应使用公共属性进行访问。 I decided to change these fields into auto-implemented properties, as I currently don't require any validation within the properties: 我决定将这些字段更改为自动实现的属性,因为我目前不需要对这些属性进行任何验证:
class Person
{
public string Name { get; set; }
public List<Thing> Things { get; set; }
public Person(string name)
{
this.Name = name;
}
}
According the MSDN page for auto-implemented properties ( https://msdn.microsoft.com/en-us/library/bb384054.aspx ), the compiler creates a private backing field for the property. 根据自动实现属性的MSDN页面( https://msdn.microsoft.com/en-us/library/bb384054.aspx ),编译器将为该属性创建一个私有支持字段。
However, with a list property I'm not sure whether the compiler automatically instantiates the list backing field , so my question is will having the lists as auto-implemented properties work as in the second example above , or do I need to instantiate the lists as well , and if so how should I do this? 但是,对于list属性, 我不确定编译器是否自动实例化列表后备字段 ,因此我的问题是将列表作为自动实现的属性像上述第二个示例中那样工作 ,还是我需要实例化列表?以及 ,如果是这样,我应该怎么做?
I'm not sure whether the compiler automatically instantiates the list backing field 我不确定编译器是否自动实例化列表后备字段
It doesn't. 没有。 If you don't instantiate it, it will be null by default. 如果不实例化它,则默认情况下为null。
do I need to instantiate the lists as well, and if so how should I do this? 我还需要实例化列表吗?如果是的话,该怎么做?
You need to instantiate it yourself. 您需要自己实例化它。 This is usually/can be done in the constructor. 这通常/可以在构造函数中完成。 Eg: 例如:
public Person(string name)
{
this.Name = name;
this.Things = new List<Thing>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.