如何从程序集中提取泛型类型?

时间:2010-08-16 10:21:54

标签: c# .net reflection interface types

我这里有一个奇怪的问题。我想提取一些泛型类型,它们从程序集实现通用接口。我可以从程序集中累积所有类型,但不能从该类型集合中搜索特定的已实现类型。这是我正在使用的代码,请指出它有什么问题?或者我如何实现目标?

using System.Reflection;
using System;
using System.Collections.Generic;

namespace TypeTest
{
    class Program
    {
        public static void Main(string[] args)
        {
            Test<int>();
            Console.ReadKey(true);
        }

        static void Test<T>(){
            var types = Assembly.GetExecutingAssembly().GetTypes();

            // It prints Types found = 4
            Console.WriteLine("Types found = {0}", types.Length); 

            var list = new List<Type>(); 

            // Searching for types of type ITest<T>      
            foreach(var type in types){
                if (type.Equals(typeof(ITest<>))) {
                    list.Add(type);
                }
            }

            // Here it prints ITest type found = 1 
            // Why? It should prints 3 instead of 1,
            // How to correct this?
            Console.WriteLine("ITest type found = {0}", list.Count); 
        }
    }

    public interface ITest<T>
    {
        void DoSomething(T item);
    }

    public class Test1<T> : ITest<T>
    {
        public void DoSomething(T item)
        {
            Console.WriteLine("From Test1 {0}", item);
        }
    }

    public class Test2<T> : ITest<T>
    {
        public void DoSomething(T item)
        {
            Console.WriteLine("From Test2 {0}", item);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

static void Test<T> ()

在主要功能的声明中,您不需要TType实例仅在类型相同时才相等,而不是一种类型可转换为另一种类型或实现另一种类型。假设您要查找使用任何参数实现ITest<>的所有类型,此检查应该有效:

if (type == typeof (ITest<>) ||
    Array.Exists   (type.GetInterfaces (), i => 
        i.IsGenericType &&
        i.GetGenericTypeDefinition () == typeof (ITest<>))) // add this type
相关问题