基本接口的通用类型

Dem*_*tom 5 c# generics reflection .net-core

我的班级结构(简化)

interface Foo<T> { }
abstract class Bar1 : Foo<SomeClass> { }
abstract class Bar2 : Foo<SomeOtherClass> { }
class FinalClass1 : Bar1 { }
class FinalClass2 : Bar2 { }
Run Code Online (Sandbox Code Playgroud)

现在,只有类型FinalClass1和FinalClass2,我需要从Foo接口获取它们各自的T类型 - FinalClass1的SomeClass和FinalClass2的SomeOtherClass.抽象类可以实现更通用的接口,但始终只有一个Foo.

  1. 如何使用反射来实现这一目标?

  2. 无论T是什么类型,我怎样才能确保类型实现Foo?就像是

bool bIsFoo = typeof(SomeType).IsAssignableFrom(Foo<>)

以上不起作用.

Ser*_*kiy 5

搜索通用接口的类型接口Foo<>.然后得到该接口的第一个泛型参数:

type.GetInterfaces()
    .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>))
    ?.GetGenericArguments().First();
Run Code Online (Sandbox Code Playgroud)

如果要检查类型是否正在实现Foo<>:

type.GetInterfaces()
    .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>))
Run Code Online (Sandbox Code Playgroud)