property for list<T> [closed]
List<T> lst = new L开发者_开发百科ist<T>();
public List<T> List
{
get { return lst; }
set { //cod...???????????????????? }
}
List<T> lst = new List<T>();
public List<T> List
{
get { return lst; }
set { lst = value; }
}
In most cases like this, you do not want a setter, effectively making the list itself read-only. In other words, anybody can change the contents of the list, but you can never give an instance of the object a new list.
From your comment above it looks like you want the setter to copy all items over, in which case you would do this:
private List<T> lst;
public List<T> List {
get { return lst; }
set { lst = new List<T>(value); }
}
But if that's all you want, I would recommend just using an auto property, to wit:
public List<T> MyList { get; set; }
Of course this raises issues of encapsulation, as Gabe pointed out.
Most often I would recommend that properties of a collection type do not have a public Set so they don't allow changing the actual collection object reference, only modify the collection. Otherwise it can lead to confusing problems if a user saves the reference to the collection and then in another part of the code sets the property to another collection. The first usage then have a reference to something that the class containing the property is not using.
public List<T> List { get; private set;}
public MyClass()
{
this.List = new List<T>();
}
or, depending on when and how you want to define your collection...
private List<T> list = new List<T>();
public List<T> List { get { return list; } }
List<T> lst = new List<T>();
public List<T> List
{
get { return lst; }
set { lst.AddRange(value); }
}
Simply encapsulate it using Studio. ;)
精彩评论