List<T> & where T :
I have simple code witch works ok:
public class Example
{
private List<SomeClass> _list = new List<SomeClass>();
开发者_C百科 public void Add(SomeClass _b) {
_list.Add(_b);
}
}
it possible to add SomeClass to _list something like this? (without specifying argument)?
public void Add<T>() where T : SomeClass
{
}
Assuming that SomeClass
has a default constructor, you can:
public void Add<T>() where T : SomeClass, new()
{
_list.Add(new T());
}
If SomeClass
does not have a default constructor then you won't be able to write new T()
and you will need to find another way of getting a T
object.
You may use generics:
public class Example<T>
{
private List<T> = _list = new List<T>();
public void Add(T element)
{
_list.Add(element);
}
}
What would you be adding? I don't see any point to that. The external consumer of Example
would not be able to add anything.
You would have to do
public void Add<T>(T _b) where T : SomeClass
{
}
But it is pretty pointless and means the same thing as you existing code.
精彩评论