什么是新的()约束在一个类定义呢? [英] What does the new() constraint do on a class definition?
问题描述
我看到这个代码示例,想知道是什么新()
约束的目的是:
公共类客户< T> :IClient其中T:IClientFactory,新的()
{
公共客户端(INT用户id){}
}
这就是所谓的'新'的约束。 下面是关于它的文档。
新的约束规定,在泛型类声明的任何类型的参数必须有一个公开参数构造函数。要使用新的约束,类型不能是抽象的。
块引用>
(重点煤矿)
基本上,你需要它时,你重新创建一个新的
T
某处类,以确保您只能在发生着变化,编译器的可以的创建一个新的实例的。I saw this code example and was wondering what the purpose of the
new()
constraint was:public class Client<T> : IClient where T : IClientFactory, new() { public Client(int UserID){ } }
解决方案That's called a "'new' constraint". Here's the documentation on it.
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
(Emphasis mine)
Basically, you need it whenever you're creating a new
T
somewhere in the class, to ensure that you're only able to pass in things which the compiler can create a new instance of.这篇关于什么是新的()约束在一个类定义呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!