在对通用类施加约束时使用new() [英] Use of new() while applying a constraint on generic class
问题描述
我已经使用泛型已有一段时间了,并且已经广泛使用它们.最近,当我在一个涉及泛型的项目中工作时,有些事情让我震惊,我希望有人可以澄清一下.假设我声明一个类如下:
Hi,
I have been using generics for quite a while and have already used them extensively.Recently when i was working on a project involving generics some thing struck me which i want somebody to please clarify. Suppose i declare a class as following:
public class Stack<t> where T : IComparable,new()
{
....
}
在这里,处于T位置的类应实现IComparable接口,并且还应实现一个默认构造函数.但是,我们也知道,如果不提供默认构造函数,则编译器会自动插入默认构造函数.那么在通用类上编写"new()"约束有什么用呢?
Here, the class which takes the position of T should implement IComparable interface and should also implement a default constructor. However we also know the fact that if we don`t provide a default constructor, the compiler automatically inserts a default constructor. So whats the use of writing a "new()" constraint on the generic class ?
推荐答案
这意味着phe无参数构造函数必须以一种或另一种方式存在. br/>
请考虑以下内容:
That means, phe parameterless constructor must exist, one way or another.
Consider the following:
public class Test1 {
public Test1(string somestring) { }
}
public class Test2<T1> where T1 : new() {
}
现在,如果我尝试定义实例
Now if I try to define an instance
Test2<Test1> testInstance = new Test2<Test1>();
那会失败,
That would fail with
''App.Test1'' must be a non-abstract type with a public parameterless constructor in order to use it as parameter ''T1'' in the generic type or method ''App.Test2<T1>''
这篇关于在对通用类施加约束时使用new()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!