简体   繁体   English

实例化 List<> 类型的属性

[英]Instantiate A Property Of Type List<>

I created a property of type List in my class我在我的班级中创建了一个 List 类型的属性

public List<string> CategoryRef { get; set; }

Now when I wanna add a string to the list I try现在当我想在列表中添加一个字符串时,我尝试

Product p=new Product();
p.CategoryRef.Add("Nick");

The compiler yells at me saying the object isnt set to an instance of an object.编译器对我大喊大叫,说对象没有设置为对象的实例。 How to I instantiate a property?如何实例化一个属性?

In the constructor you need to say在构造函数中你需要说

this.CategoryRef = new List<string>();

All that这一切

public List<string> CategoryRef { get; set; }

does is declare an auto-property of type List<string> named CategoryRef . do 是声明一个名为CategoryRef List<string>类型的自动属性。 Implicitly behind this auto-property is a backing field, but that backing field receives the default value for objects of type List<string> .这个自动属性的背后是一个支持字段,但该支持字段接收List<string>类型对象的默认值。 Therefore, by default, the backing field is null and this is why you must set it in the constructor (or somewhere else but before you use it for the first time).因此,默认情况下,支持字段为null ,这就是为什么您必须在构造函数中(或在您第一次使用它之前的其他地方)设置它的原因。

Finally, you probably should not be exposing the setter publicly.最后,您可能不应该公开暴露 setter。 At a minimum, it is better to say至少,最好说

public List<string> CategoryRef { get; private set; }

Do you really want clients of your class to be able to assign a new list to CategoryRef ?您真的希望您班级的客户能够为CategoryRef分配一个新列表吗? Probably not.可能不是。

And in situations like this, I actually prefer a manual property so that I can make the backing field readonly.在这种情况下,我实际上更喜欢手动属性,以便我可以将支持字段设为只读。

private readonly List<string> categoryRef = new List<string>();
public List<string> CategoryRef {
    get {
        return this.categoryRef;
    }
}

In the constructor of the object, you should have a line that sets the property to a new list.在对象的构造函数中,您应该有一行将属性设置为新列表。

public class Product{
   public Product()
   {
      CategoryRef = new List<string>();
   }

   public List<string> CategoryRef{ get; set;}
}

I would perhaps try something like the below我也许会尝试像下面这样的

public class Product{

   public List<string> CategoryRef{ get; set;} = new List<string>();

}

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

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