开发者

How to extract generic types from an assembly?

I have a peculiar problem here. I want to extract some generic types, which implements a generic interface from an assembly. I can accumulate all the types from the assembly but can not search for a particular implemented type from that type collection. Here are my code I am using, can you please point out what is the wrong with it? Or how can I achieve the goal?

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 D开发者_如何学GooSomething(T item)
        {
            Console.WriteLine("From Test2 {0}", item);
        }
    }
}


static void Test<T> ()

You don't need T in the declaration of your main function. Type instances are equal only if types are the same, not if one type is convertible to the other or implements the other. Supposing you want to find all types which implement ITest<> with any argument, this check should work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜