【发布时间】:2020-04-03 07:07:06
【问题描述】:
我有 2 个具有不同约束的类,我想在通用函数中有条件地为它们创建 obj。下面的例子。
public class Foo1<T>
where T : class, Interface1, new()
{
// do sth...
}
public class Foo2<T>
where T : class, Interface2, new()
{
//do sth...
}
public static void Create<T>()
{
if(typeof(Interface1).IsAssignableFrom(typeof(T))
{
var obj = new Foo1();
//...
} else if (typeof(Interface2).IsAssignableFrom(typeof(T))
{
var obj = new Foo1();
//...
}
}
我收到错误“没有从 T 到 Interface1/2 的隐式引用转换”。 问题和How to conditionally invoke a generic method with constraints?类似,不过我可以找个地方补充一下(动态)。
【问题讨论】:
标签: c# constraints