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.
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) ...
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With