泛型类的缺省构造函数语法是什么?

在 C # 中是否禁止为泛型类实现缺省构造函数?

如果没有,为什么下面的代码不编译? (当我删除 <T>它编译)

那么,为泛型类定义缺省构造函数的正确方法是什么呢?

public class Cell<T>
{
public Cell<T>()
{
}
}

编译时错误 : 错误1无效令牌’(’在类、结构或接口成员声明中

61292 次浏览

You don't provide the type parameter in the constructor. This is how you should do it.

public class Cell<T>
{
public Cell()
{
}
}

And if you need the Type as a property:

public class Cell<T>
{
public Cell()
{
TheType = typeof(T);
}


public Type TheType { get;}
}

And if you need to inject an instance of the type:

public class Cell<T>
{
public T Thing { get; }


public Cell(T thing)
{
Thing = thing;
}
}