gpt4 book ai didi

c# - 获取实现特定开放通用类型的所有类型

转载 作者:IT王子 更新时间:2023-10-29 03:55:30 26 4
gpt4 key购买 nike

如何获取实现特定开放泛型类型的所有类型?

例如:

public interface IUserRepository : IRepository<User>

查找所有实现 IRepository<> 的类型.

public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
...
}

最佳答案

这将返回继承通用基类的所有类型。并非所有类型都继承通用接口(interface)。

var AllTypesOfIRepository = from x in Assembly.GetAssembly(typeof(AnyTypeInTargetAssembly)).GetTypes()
let y = x.BaseType
where !x.IsAbstract && !x.IsInterface &&
y != null && y.IsGenericType &&
y.GetGenericTypeDefinition() == typeof(IRepository<>)
select x;

这将返回所有类型,包括在其继承链中具有开放泛型类型的接口(interface)、抽象和具体类型。

public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
return from x in assembly.GetTypes()
from z in x.GetInterfaces()
let y = x.BaseType
where
(y != null && y.IsGenericType &&
openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
(z.IsGenericType &&
openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
select x;
}

第二种方法将在本例中找到ConcreteUserRepoIUserRepository:

public class ConcreteUserRepo : IUserRepository
{}

public interface IUserRepository : IRepository<User>
{}

public interface IRepository<User>
{}

public class User
{}

关于c# - 获取实现特定开放通用类型的所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com