- 已编辑 -
但是当我得到一个复杂的泛型:
class Class<T> : Interface<T, List<T>>
{
// ...
}
我如何获得typeof(Interface<, List<>>)
?
// typeof(Interface<, List<>>)
编译错误
我真的不想使用typeof(Class<>).GetInterfaces()[0]
。
有什么想法吗?
答案 0 :(得分:2)
您需要准确传递所有通用参数,以确定它们在界面中的显示方式。
int i = 1; // just for example, any suitable type
var type = i.GetType();
var listType = typeof(List<>).MakeGenericType(type);
var intfType = typeof(I1<,>).MakeGenericType(type, listType);
修改强>
如果我最终正确理解了OP - 你不能这样做。类型可以是打开或关闭。您可以使用其他泛型和非泛型类型的混合来定义泛型类型(类和接口),但它可以专门用于定义类型。您无法在运行时从这些定义构造部分关闭或部分修改的泛型类型。要做你想做的事,你需要引入另一个接口,它只定义一个通用参数,然后用它操作:
interface GenericInterface<T1, T2>
{
}
interface ListInterface<T> : GenericInterface<T, List<T>>
{
}
class Class1<T> : ListInterface<T>
{
// ...
}
var blah = typeof(ListInterface<>); // this is the exact interface that Class1 implements