从提供的类型返回通用接口实现的类型

时间:2013-05-11 13:34:35

标签: c# system.reflection

给定一个实现接口的类:

public interface DomainEventSubscriber<T>
{
    void HandleEvent(T domainEvent);
}

public class TestEventHandler : DomainEventSubscriber<TestEvent1>, DomainEventSubscriber<OtherTestEvent1>
{
    public void HandleEvent(TestEvent1 domainEvent)
    {
    }

    public void HandleEvent(OtherTestEvent1 domainEvent)
    {
        throw new NotImplementedException();
    }
}

我想返回已实现的类型,即

static Type[] FindTypesForDomainEventSubscriberOfT(Type type)
{
     // given a TestEventHandler type, I should return a collection of { TestEvent1, OtherTestEvent1 }
}

请问这怎么办?

2 个答案:

答案 0 :(得分:3)

听起来你想要这样的东西:

static Type[] FindTypesForDomainEventSubscriberOfT(Type type)
{
    return type.GetInterfaces()
      .Where(x => x.IsGenericType &&
                  x.GetGenericTypeDefinition() == typeof(DomainEventSubscriber<>))
      .Select(x => x.GetGenericArguments()[0])
      .ToArray(); 
}

请注意,这可能会导致返回类型参数。例如,如果你有:

public class Foo<T> : DomainEventSubscriber<T>

然后它将返回TFoo<T>的类型参数。如果您不想这样,可以插入:

.Where(x => !x.IsGenericParameter)
ToArray来电之前

(我还建议您按照.NET命名约定重命名接口,使其具有I前缀。)

答案 1 :(得分:0)

我猜您正在寻找Type.GetGenericTypeDefinition Method

private static void DisplayTypeInfo(Type t)
{
    Console.WriteLine("\r\n{0}", t);
    Console.WriteLine("\tIs this a generic type definition? {0}", 
        t.IsGenericTypeDefinition);
    Console.WriteLine("\tIs it a generic type? {0}", 
        t.IsGenericType);
    Type[] typeArguments = t.GetGenericArguments();
    Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
    foreach (Type tParam in typeArguments)
    {
        Console.WriteLine("\t\t{0}", tParam);
    }
}