Zai*_*sud 5 c# generics c#-3.0 c#-2.0 c#-4.0
请考虑以下代码示例,其中Concrete派生自Base:
class Base{}
class Concrete : Base {}
static void Foo<T>() where T : Base
{
if (typeof(Concrete).IsAssignableFrom(typeof(T)))
{
var x = new Bar<T>(); // compile error on this line
}
}
class Bar<T> where T : Concrete
{
}
Run Code Online (Sandbox Code Playgroud)
在我遇到编译错误的行上,我已经检查过泛型参数是否可以赋值给Concrete类型.所以理论上我认为应该有一种方法来创建Bar类的实例.
有什么办法可以删除编译错误吗?我想不出一种方式来论证.
编译错误的全文:
错误14类型"T"不能用作泛型类型或方法"Bar"中的类型参数"T".没有从'T'到'Concrete'的隐式引用转换.
编译器无法知道当前约束 Base 的 T 实际上是 Concrete,即使您之前对其进行了测试。
所以:
Type type = typeof(Bar<>);
Type generic = type.MakeGenericType(typeof(T));
var x = Activator.CreateInstance(generic);
Run Code Online (Sandbox Code Playgroud)
不要让它有机会去做。