rav*_*ven 4 c# generics type-constraints
我试图理解C#中泛型类型参数的约束.where T : new()约束的目的是什么?为什么你需要坚持类型参数有一个公共无参数构造函数?
编辑: 我一定错过了什么.评价最高的答案表示公共无参数构造函数是实例化泛型类型所必需的.如果是这种情况,为什么这个代码编译并运行?
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//class Foo has no public parameterless constructor
var test = new genericClass<Foo>();
}
}
class genericClass<T> where T : new()
{
T test = new T(); //yet no problem instantiating
}
class Foo
{
//no public parameterless constructor here
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:在他的评论中,gabe提醒我,如果我没有定义构造函数,编译器默认提供无参数构造函数.因此,我的示例中的类Foo实际上确实有一个公共无参数构造函数.
Gre*_*reg 12
如果要实例化新的T.
void MyMethod<T>() where T : new()
{
T foo = new T();
...
}
Run Code Online (Sandbox Code Playgroud)