我正在使用泛型类和约束条件。以下是我的课程。泛型类和约束条件
public class GenericList<T> where T : new()
{
private Node head;
// constructor
public GenericList()
{
head = null;
}
}
当我与整数创建对象,它工作正常
GenericList<int> list = new GenericList<int>();
但是,当我用绳子尝试它给了我下面的编译时错误。
GenericList<string> list1 = new GenericList<string>();
“字符串”必须是一个非抽象类型,以便在通用类型或方法“GenericTest.GenericList” 还当我过去的基准参数,以使用它作为参数“T”的公开参数构造像任何自定义类,它工作正常。
字符串的问题是什么?
康斯坦丁已经解释了为什么它会失败 - 但为什么你对T开头的约束呢?你想什么时候调用'new T()'?这就是所有的约束条件。 –
这些都没有解释为什么你想要无参数的构造函数约束。再次,你想在'GenericList'内调用'new T()'? –