简体   繁体   English

声明泛型类时 new() 的目的是什么?

[英]What is the purpose of new() while declaration of a generic class?

What is the purpose of new() while declaration of BaseEntityCollection class?声明 BaseEntityCollection 类时 new() 的目的是什么?
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 ..."如果我要删除它,我会收到一条错误消息,显示以下消息“T 必须是具有公共无参数构造函数的非抽象类型才能将其用作参数......”

public abstract 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.这意味着无论您为T指定什么类,它都有一个默认(无参数)构造函数。

Therefore, in the generic class, you can do new T() and it will create a new object of type T.因此,在泛型类中,您可以执行new T()并且它将创建一个类型为 T 的新对象。

Writing new() forces the parameter to have a default constructor.编写new()强制参数具有默认构造函数。

Without it, you can't write new T() .没有它,你就不能写new T()
Your error happens when you try to pass a non- new() type as a new() 'd parameter.当您尝试将非new()类型作为new() 'd 参数传递时,会发生错误。


Also, do not inherit List<T> .另外,不要继承List<T>
Instead, you should inherit Collection<T> , which is designed for inheritance.相反,您应该继承专为继承而设计的Collection<T>

The type T has to have a parameterless constructor.类型T必须有一个无参数的构造函数。 This enables you to create new instances by doing var t = new T() which would be impossible otherwise.这使您能够通过执行var t = new T()创建新实例,否则这是不可能的。

它是通用约束的符号:必须具有(公共)无参数构造函数。

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.我不确定你在这里做什么,但我认为这违反了 Liskov 的规则。 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.使用约束“new()”将只允许您使用具有无参数构造函数的泛型类型。 This can be useful for things like serialization, or factory-type methods, where you need to create an object of type T.这对于诸如序列化或工厂类型方法之类的事情很有用,您需要在其中创建类型 T 的对象。

Here are some other generic type constraints: http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx以下是其他一些通用类型约束: 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 .在这种情况下,它是一个新的 Constraint

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

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