泛型类和约束

时间:2012-11-30 07:02:15

标签: c# .net string generics

我正在使用Generic类和Constraint。以下是我的班级。

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>();

'string'必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法'GenericTest.GenericList'中将其用作参数'T' 当我像任何自定义类一样传递引用参数时,它工作正常。

字符串有什么问题?

2 个答案:

答案 0 :(得分:3)

String Class没有公共无参数构造函数 ..这就是new()约束不适用于它的原因。

阅读Constraints on Type Parameters (C# Programming Guide)

  

其中T:new()

     

type参数必须具有公共无参数构造函数。什么时候   与其他约束一起使用时,new()约束必须是   最后指定。

答案 1 :(得分:2)

String类型具有公共无参数构造函数是没有意义的,因为String不可变,这意味着如果String具有此构造函数,那么它将必须创建一个空的字符串对象,这只是愚蠢的,因为创建后你无法改变它。

相关问题