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

发布于 2024-12-23 04:23:36 字数 323 浏览 4 评论 0原文

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

例如:

public interface IUserRepository : IRepository<User>

查找所有实现 IRepository 的类型。

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

How do I get all types that implementing a specific open generic type?

For instance:

public interface IUserRepository : IRepository<User>

Find all types that implement IRepository<>.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

残花月 2024-12-30 04:23:36

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

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;

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

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
{}

This will return all types that inherit a generic base class. Not all types that inherit a generic 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;

This will return all types, including interfaces, abstracts, and concrete types that have the open generic type in its inheritance chain.

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;
}

This second method will find ConcreteUserRepo and IUserRepository in this example:

public class ConcreteUserRepo : IUserRepository
{}

public interface IUserRepository : IRepository<User>
{}

public interface IRepository<User>
{}

public class User
{}
猫瑾少女 2024-12-30 04:23:36

不使用 LINQ 实现的解决方案,搜索泛型和非泛型接口,过滤类的返回类型。

public static class SampleCode
{
    public static void Main()
    {
        IList<Type> loadableTypes;

        // instance the dummy class used to find the current assembly
        DummyClass dc = new DummyClass();

        loadableTypes = GetClassesImplementingAnInterface(dc.GetType().Assembly, typeof(IMsgXX)).Item2;
        foreach (var item in loadableTypes) {Console.WriteLine("1: " + item);}
        // print
        // 1: Start2.MessageHandlerXY

        loadableTypes = GetClassesImplementingAnInterface(dc.GetType().Assembly, typeof(IHandleMessageG<>)).Item2;
        foreach (var item in loadableTypes) { Console.WriteLine("2: " + item); }
        // print
        // 2: Start2.MessageHandlerXY
        // 2: Start2.MessageHandlerZZ
    }

    ///<summary>Read all classes in an assembly that implement an interface (generic, or not generic)</summary>
    //
    // some references
    // return all types implementing an interface
    // http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface/12602220#12602220
    // http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx/
    // http://stackoverflow.com/questions/7889228/how-to-prevent-reflectiontypeloadexception-when-calling-assembly-gettypes
    // return all types implementing a generic interface
    // http://stackoverflow.com/questions/33694960/find-all-types-implementing-a-certain-generic-interface-with-specific-t-type
    // http://stackoverflow.com/questions/8645430/get-all-types-implementing-specific-open-generic-type
    // http://stackoverflow.com/questions/1121834/finding-out-if-a-type-implements-a-generic-interface
    // http://stackoverflow.com/questions/5849210/net-getting-all-implementations-of-a-generic-interface
    public static Tuple<bool, IList<Type>> GetClassesImplementingAnInterface(Assembly assemblyToScan, Type implementedInterface)
    {
        if (assemblyToScan == null)
            return Tuple.Create(false, (IList<Type>)null);

        if (implementedInterface == null || !implementedInterface.IsInterface)
            return Tuple.Create(false, (IList<Type>)null);

        IEnumerable<Type> typesInTheAssembly;

        try
        {
            typesInTheAssembly = assemblyToScan.GetTypes();
        }
        catch (ReflectionTypeLoadException e)
        {
            typesInTheAssembly = e.Types.Where(t => t != null);
        }

        IList<Type> classesImplementingInterface = new List<Type>();

        // if the interface is a generic interface
        if (implementedInterface.IsGenericType)
        {
            foreach (var typeInTheAssembly in typesInTheAssembly)
            {
                if (typeInTheAssembly.IsClass)
                {
                    var typeInterfaces = typeInTheAssembly.GetInterfaces();
                    foreach (var typeInterface in typeInterfaces)
                    {
                        if (typeInterface.IsGenericType)
                        {
                            var typeGenericInterface = typeInterface.GetGenericTypeDefinition();
                            var implementedGenericInterface = implementedInterface.GetGenericTypeDefinition();

                            if (typeGenericInterface == implementedGenericInterface)
                            {
                                classesImplementingInterface.Add(typeInTheAssembly);
                            }
                        }
                    }
                }
            }
        }
        else
        {
            foreach (var typeInTheAssembly in typesInTheAssembly)
            {
                if (typeInTheAssembly.IsClass)
                {
                    // if the interface is a non-generic interface
                    if (implementedInterface.IsAssignableFrom(typeInTheAssembly))
                    {
                        classesImplementingInterface.Add(typeInTheAssembly);
                    }
                }
            }
        }
        return Tuple.Create(true, classesImplementingInterface);
    }
}

public class DummyClass
{
}

public interface IHandleMessageG<T>
{
}

public interface IHandleMessage
{
}

public interface IMsgXX
{
}

public interface IMsgXY
{
}

public interface IMsgZZ
{
}

public class MessageHandlerXY : IHandleMessageG<IMsgXY>, IHandleMessage, IMsgXX
{
    public string Handle(string a)
    {
        return "aaa";
    }
}

public class MessageHandlerZZ : IHandleMessageG<IMsgZZ>, IHandleMessage
{
    public string Handle(string a)
    {
        return "bbb";
    }
}

Solution implemented without LINQ, searching both generic and non generic interfaces, filtering the return type to classes.

public static class SampleCode
{
    public static void Main()
    {
        IList<Type> loadableTypes;

        // instance the dummy class used to find the current assembly
        DummyClass dc = new DummyClass();

        loadableTypes = GetClassesImplementingAnInterface(dc.GetType().Assembly, typeof(IMsgXX)).Item2;
        foreach (var item in loadableTypes) {Console.WriteLine("1: " + item);}
        // print
        // 1: Start2.MessageHandlerXY

        loadableTypes = GetClassesImplementingAnInterface(dc.GetType().Assembly, typeof(IHandleMessageG<>)).Item2;
        foreach (var item in loadableTypes) { Console.WriteLine("2: " + item); }
        // print
        // 2: Start2.MessageHandlerXY
        // 2: Start2.MessageHandlerZZ
    }

    ///<summary>Read all classes in an assembly that implement an interface (generic, or not generic)</summary>
    //
    // some references
    // return all types implementing an interface
    // http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface/12602220#12602220
    // http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx/
    // http://stackoverflow.com/questions/7889228/how-to-prevent-reflectiontypeloadexception-when-calling-assembly-gettypes
    // return all types implementing a generic interface
    // http://stackoverflow.com/questions/33694960/find-all-types-implementing-a-certain-generic-interface-with-specific-t-type
    // http://stackoverflow.com/questions/8645430/get-all-types-implementing-specific-open-generic-type
    // http://stackoverflow.com/questions/1121834/finding-out-if-a-type-implements-a-generic-interface
    // http://stackoverflow.com/questions/5849210/net-getting-all-implementations-of-a-generic-interface
    public static Tuple<bool, IList<Type>> GetClassesImplementingAnInterface(Assembly assemblyToScan, Type implementedInterface)
    {
        if (assemblyToScan == null)
            return Tuple.Create(false, (IList<Type>)null);

        if (implementedInterface == null || !implementedInterface.IsInterface)
            return Tuple.Create(false, (IList<Type>)null);

        IEnumerable<Type> typesInTheAssembly;

        try
        {
            typesInTheAssembly = assemblyToScan.GetTypes();
        }
        catch (ReflectionTypeLoadException e)
        {
            typesInTheAssembly = e.Types.Where(t => t != null);
        }

        IList<Type> classesImplementingInterface = new List<Type>();

        // if the interface is a generic interface
        if (implementedInterface.IsGenericType)
        {
            foreach (var typeInTheAssembly in typesInTheAssembly)
            {
                if (typeInTheAssembly.IsClass)
                {
                    var typeInterfaces = typeInTheAssembly.GetInterfaces();
                    foreach (var typeInterface in typeInterfaces)
                    {
                        if (typeInterface.IsGenericType)
                        {
                            var typeGenericInterface = typeInterface.GetGenericTypeDefinition();
                            var implementedGenericInterface = implementedInterface.GetGenericTypeDefinition();

                            if (typeGenericInterface == implementedGenericInterface)
                            {
                                classesImplementingInterface.Add(typeInTheAssembly);
                            }
                        }
                    }
                }
            }
        }
        else
        {
            foreach (var typeInTheAssembly in typesInTheAssembly)
            {
                if (typeInTheAssembly.IsClass)
                {
                    // if the interface is a non-generic interface
                    if (implementedInterface.IsAssignableFrom(typeInTheAssembly))
                    {
                        classesImplementingInterface.Add(typeInTheAssembly);
                    }
                }
            }
        }
        return Tuple.Create(true, classesImplementingInterface);
    }
}

public class DummyClass
{
}

public interface IHandleMessageG<T>
{
}

public interface IHandleMessage
{
}

public interface IMsgXX
{
}

public interface IMsgXY
{
}

public interface IMsgZZ
{
}

public class MessageHandlerXY : IHandleMessageG<IMsgXY>, IHandleMessage, IMsgXX
{
    public string Handle(string a)
    {
        return "aaa";
    }
}

public class MessageHandlerZZ : IHandleMessageG<IMsgZZ>, IHandleMessage
{
    public string Handle(string a)
    {
        return "bbb";
    }
}
献世佛 2024-12-30 04:23:36

你可以尝试

openGenericType.IsAssignableFrom(myType.GetGenericTypeDefinition()) 

或者

myType.GetInterfaces().Any(i => i.GetGenericTypeDefinition() = openGenericType)

You could try

openGenericType.IsAssignableFrom(myType.GetGenericTypeDefinition()) 

or

myType.GetInterfaces().Any(i => i.GetGenericTypeDefinition() = openGenericType)
腻橙味 2024-12-30 04:23:36

您可以使用以下代码获取所有实现 IRepository 接口的类型:

List<Type> typesImplementingIRepository = new List<Type>();
IEnumerable<Type> allTypesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();

foreach (Type type in allTypesInThisAssembly)
{
    if (type.GetInterface(typeof(IRepository<>).Name.ToString()) != null)
    {
        typesImplementingIRepository.Add(type);
    }
}

You can use the following code to get all types that implement IRepository<> interface:

List<Type> typesImplementingIRepository = new List<Type>();
IEnumerable<Type> allTypesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();

foreach (Type type in allTypesInThisAssembly)
{
    if (type.GetInterface(typeof(IRepository<>).Name.ToString()) != null)
    {
        typesImplementingIRepository.Add(type);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文