Instantiate A Property Of Type List<>
I created a property of type List in my class
public List<string> CategoryRef { get; set; 开发者_如何学C}
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
. Implicitly behind this auto-property is a backing field, but that backing field receives the default value for objects of type 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).
Finally, you probably should not be exposing the setter publicly. 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
? 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>();
}
精彩评论