What is the purpose of new() while declaration of a generic class?
What is the purpose of new() while declaration of BaseEntityCollection class?
If I'm going to remove it, I got an error with the following message "T must be a non-abstract type with a public parameterless constructor in order to use it as parameter ..."public abstract 开发者_StackOverflow中文版partial class BaseEntityCollection<T> :
List<T> where T : BaseEntity, new()
It means that whatever class you specify for T
, it has a default (no parameters) constructor.
Therefore, in the generic class, you can do new T()
and it will create a new object of type T.
Writing new()
forces the parameter to have a default constructor.
Without it, you can't write new T()
.
Your error happens when you try to pass a non-new()
type as a new()
'd parameter.
Also, do not inherit List<T>
.
Instead, you should inherit Collection<T>
, which is designed for inheritance.
The type T
has to have a parameterless constructor. This enables you to create new instances by doing var t = new T()
which would be impossible otherwise.
It is the notation for the generic constraint: Must have (public) parameterless constructor.
This means that your generic type has to have parameterless constructor.
BaseEntityCollection<T> : List<T>
I am not sure what are you doing here, but I think it is against Liskov's rule. Check your hierarchy.
Constraints on Type Parameters
That is one of the possible "generic type constraints" you can associate with your generic type. Using the constraint "new()" will only allow you to use a generic type if it has a parameterless constructor. This can be useful for things like serialization, or factory-type methods, where you need to create an object of type T.
Here are some other generic type constraints: http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx
It's a generic constraint. In this case, it's a the new Constraint.
精彩评论