编译器错误 CS0310

类型“typename”必须是具有公共的无参数构造函数的非抽象类型,才能用作泛型类型或方法“generic”中的参数“parameter”

泛型类型或方法在其 where 子句中定义了一个 new() 约束,因此任何类型必须具有公共的无参数构造函数,才能用作该泛型类型或方法的类型参数。 若要避免此错误,请确保类型具有正确的构造函数,或修改泛型类型或方法的约束子句。

示例

下面的示例生成 CS0310:

// CS0310.cs  
using System;  
  
class G<T> where T : new()  
{  
    T t;  
  
    public G()  
    {  
        t = new T();  
        Console.WriteLine(t);  
    }  
}  
  
class B  
{  
    private B() { }  
    // Try this instead:  
    // public B() { }  
}  
  
class CMain  
{  
    public static void Main()  
    {  
        G<B> g = new G<B>();   // CS0310  
        Console.WriteLine(g.ToString());  
    }  
}