0

给定一个实现接口的类:

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

请问这怎么做?

4

2 回答 2

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>

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

.Where(x => !x.IsGenericParameter)

通话前ToArray

(我还建议您I按照 .NET 命名约定重命名接口以使用前缀。)

于 2013-05-11T13:42:26.757 回答
0

我猜你正在寻找Type.GetGenericTypeDefinition 方法

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);
    }
}
于 2013-05-11T13:43:00.290 回答