2010-08-16 3 views
0

여기에 특이한 문제가 있습니다. 어셈블리에서 제네릭 인터페이스를 구현하는 일부 일반 형식을 추출하려고합니다. 어셈블리에서 모든 형식을 누적 할 수 있지만 해당 형식 컬렉션에서 특정 구현 된 형식을 검색 할 수 없습니다. 여기에 제가 사용하고있는 코드가 있습니다, 당신이 잘못된 점을 지적 해주시겠습니까? 또는 어떻게 목표를 달성 할 수 있습니까?어셈블리에서 제네릭 형식을 추출하는 방법은 무엇입니까?

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

답변

2
static void Test<T>() 

당신은 당신의 주요 기능의 선언에 T 필요하지 않습니다. Type 인스턴스는 유형이 동일 할 때만 동일하고 하나의 유형이 다른 유형으로 변환 가능하거나 다른 유형을 구현하는 경우가 아닙니다. 당신이 어떤 인수를 ITest<>를 구현하는 모든 유형을 찾으려면 가정하면,이 검사가 작동합니다 : 내가 Linq에 표현에 문제가 있다고 생각

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

을, 당신은 내가에서 내가 아니므로, 포함 사용할 수 없습니다 대리자의 Type 객체입니다. –

+0

사용해야합니다 - 모든 - 대신 - 포함 -. 그러나 어쨌든 나에게 조언을 주신 것에 대해 많은 감사를드립니다. –

+0

고정 - 생각하지 않고 직접 내 확장 방법을 사용했습니다 (너무 편리). 예,'Any' 또는'Array.Exists'를 사용하십시오. –

관련 문제