Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of Java Class<? extends Base>?

Tags:

c#

I'd like to be able to write a method in C# similar to how I would in Java... To pass in a Class object that is a subclass of some super class... but the best I can find for C# is the following:

public void someMethod(Type t) {
  if (t == typeof(SomeType)) ...
}

Is there any way I can enforce in the method signature that the parameter has to be either the type SomeType or one of its inheritors?

I'm not looking to pass in an instance of said Type. I want to pass the Type itself in as a parameter.

Edit

Here's a bit of context.

I want to make an EventManager class that contains a Dictionary<SomeEventType, ICollection<EventHandler>> object, and a method registerEventHandler(Type t, EventHandler eh) that maps a given Type to an EventHandler.

In Java, I would accomplish it as such:

private static Map<Class<? extends Event>, Collection<EventHandler>> eventHandlers;

public static void registerListener(Class<? extends Event> event, EventHandler handler) {
  if (eventHandlers.get(event) == null) {
    HashMap<EventHandler> handlers = new HashMap<EventHandler>()
    eventHandlers.put(event, handlers) ...
  }
}
like image 904
Mirrana Avatar asked Nov 01 '14 01:11

Mirrana


Video Answer


1 Answers

You could use a generic constraint.

public void someMethod<T>() where T : SomeType {
    Type myType = typeof(T);

    // do something with myType
}

Here's an implementation of your desired use case.

class EventManager {
    public Dictionary<Type, ICollection<EventHandler>> 
        HandlerMap = new Dictionary<Type, ICollection<EventHandler>>();

    public void RegisterEventHandler<TEvent>(EventHandler eh) 
        where TEvent: SomeEventType 
    {
        Type eventType = typeof(TEvent);

        if (!HandlerMap.ContainsKey(eventType)) {
            HandlerMap[eventType] = new List<EventHandler>();
        }

        HandlerMap[eventType].Add(eh);
    }
}

You would call it like this.

var em = new EventManager();
EventHandler eh = null; // or whatever
em.RegisterEventHandler<SpecificEventType>(eh);
like image 55
recursive Avatar answered Oct 06 '22 00:10

recursive