C# 泛型类的默认构造函数的语法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9701106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the syntax for a default constructor for a generic class?
提问by pencilCake
Is it forbidden in C# to implement a default constructor for a generic class?
在 C# 中是否禁止为泛型类实现默认构造函数?
If not, why the code below does not compile? (When I remove <T>it compiles though)
如果没有,为什么下面的代码不能编译?(当我删除<T>它时,它会编译)
What is the correct way of defining a default constructor for a generic class then?
那么为泛型类定义默认构造函数的正确方法是什么?
public class Cell<T>
{
public Cell<T>()
{
}
}
Compile Time Error: Error 1 Invalid token '(' in class, struct, or interface member declaration
编译时错误:错误 1 类、结构或接口成员声明中的无效标记“(”
采纳答案by Trevor Pilley
You don't provide the type parameter in the constructor. This is how you should do it.
您不在构造函数中提供类型参数。这就是你应该做的。
public class Cell<T>
{
public Cell()
{
}
}
回答by RogerW
And if you need the Type as a property:
如果您需要 Type 作为属性:
public class Cell<T>
{
public Cell()
{
TheType = typeof(T);
}
public Type TheType { get;}
}
回答by Peerhenry
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;
}
}

