【发布时间】:2016-04-18 15:22:05
【问题描述】:
这是我的代码:
void DoSomething<T>()
{
var constructor = typeof(T).GetConstructor(null);
if(constructor != null)
{
DoSomethingElse<T>(); // compiler error
}
else
{
//...
}
}
void DoSomethingElse<T>() where T:new()
{
T x = new T();
//...
}
有没有办法让编译器相信 T 是合法的 T:new()?
【问题讨论】:
-
嗯,不。显然,编译器不能那样工作:) 你还需要在你的第一个方法中添加
new()约束。 -
不能。 DoSomething 需要适用于所有类型,而不仅仅是具有默认构造函数的类型。
-
hmm 那么你可以尝试使用反射调用
DoSomethingElse。