简体   繁体   中英

Return types of generic interface implementations from a provided type

Given a class that implements an interface:

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

I would like to return the types that are implemented, ie

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

How can this be done please?

It sounds like you want something like:

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

Note that this could end up returning type parameters. For example, if you had:

public class Foo<T> : DomainEventSubscriber<T>

then it would return T , the type parameter for Foo<T> . If you don't want that, you could insert:

.Where(x => !x.IsGenericParameter)

before the ToArray call.

(I'd also recommend that you rename your interface to have an I prefix, following .NET naming conventions.)

I guess you are looking for the 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM