ist*_*pin 7 .net c# reflection
我想创建一个方法,该方法返回一个类型(或 IEnumerable 类型),该类型实现一个采用类型参数的特定接口——但是我想通过该泛型类型参数本身进行搜索。作为示例,这更容易演示:
我想要的方法签名:
public IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam, Type specificTypeParameter)
Run Code Online (Sandbox Code Playgroud)
然后如果我有以下对象
public interface IRepository<T> { };
public class FooRepo : IRepository<Foo> { };
public class DifferentFooRepo : IRepository<Foo> {};
Run Code Online (Sandbox Code Playgroud)
然后我希望能够做到:
var repos = GetByInterfaceAndGeneric(typeof(IRepository<>), typeof(Foo));
Run Code Online (Sandbox Code Playgroud)
并获得一个包含类型FooRepo和的 IEnumerable DifferentFooRepo。
这与此问题非常相似,但是使用该示例,我想按两者IRepository<>和 by进行搜索User。
为了重构@lucky的答案,我更喜欢将类型与泛型类型定义进行比较,而不是使用类型名称:
static readonly Type GenericIEnumerableType = typeof(IEnumerable<>);
//Find all types that implement IEnumerable<T>
static IEnumerable<T> FindAllEnumerableTypes<T>(Assembly assembly) =>
assembly
.GetTypes()
.Where(type =>
type
.GetInterfaces()
.Any(interf =>
interf.IsGenericType
&& interf.GetGenericTypeDefinition() == GenericIEnumerableType
&& interf.GenericTypeArguments.Single() == typeof(T)));
Run Code Online (Sandbox Code Playgroud)
或者,您可以检查是否interf可以从GenericIEnumerableType.MakeGenericType(typeof(T))或相反分配。