【问题标题】:Check if a Type derives from a Interface with more than one Generic Argument检查类型是否派生自具有多个通用参数的接口
【发布时间】:2023-03-08 05:29:02
【问题描述】:

我有一个关于使用反射加载类型的问题。我试图通过实现具有两个通用参数的接口的那些来过滤程序集中的类型列表。我不打算明确说明哪些类型是那些泛型参数,因为我想要所有实现接口的类,但是每当我尝试使用typeof(IExample<>) 时,它都会被标记为错误。但是,可以使用只有一个通用参数的接口来做到这一点。 我真的很感激这方面的一些帮助!在此先感谢:)

public interface IExample<T, E>
{
}

这就是我的界面的样子。 然后我目前必须实现它的类。

public class C 
{
}

public class A : IExample<string, C>
{
}

Public class B : IExample<XMLDocument, C>
{
}

【问题讨论】:

    标签: c# generics reflection


    【解决方案1】:

    您与我可以从您的问题中检查的内容相差不远。为了得到正确的泛型类型,没有任何泛型参数你需要调用typeof(IExample&lt;,&gt;),注意有一个逗号!


    关于如何获取这些类型的问题的另一部分,您可以执行以下操作:

    public static IEnumerable<Type> GetTypesWithGenericArguments(Assembly assembly, Type implementingInterface)
    {
        var types = assembly.GetTypes();
    
        // Loop over all Types in the assembly
        foreach (var type in types)
        {
            // Skipping all Types which aren't classes
            if (!type.IsClass)
                continue;
    
            var implementedInterfaces = type.GetInterfaces();
    
            // Loop over all interfaces the type implements
            foreach (var implementedInterface in implementedInterfaces)
            {
                // Return the type if it one of its interfaces are matching the implementingInterface
                if (implementedInterface.IsGenericType && implementedInterface.GetGenericTypeDefinition() == implementingInterface)
                {
                    yield return type;
                    // You can leave the loop, since you don't need to check the other
                    // interfaces, since you already found the one you were searching for.
                    break; 
                }
            }
        }
    }
    

    可以这样使用:

    public static void Main(string[] args)
    {
        foreach (var item in GetTypesWithGenericArguments(Assembly.GetCallingAssembly(), typeof(IExample<,>)))
        {
            Console.WriteLine(item.Name);
        }
    
        // This would print to the Console:
        // A
        // B
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 1970-01-01
      • 2012-08-09
      • 2021-04-13
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多