Generic methods with constraints that are generic
Asked Answered
C

2

5

What I want to do is have a method that takes a generic type as a parameter with a constraint. However, the constraint's type also has a second generic type, but I want the method to work regardless of what the second typing is:

public class IEvent<T> where T : EventArgs { }
public class EventManager
{
    public void DoMethod<T>() where T: IEvent<???>
    {
    }
}

Specifically, I'm trying to have my EventManager class receive any kind of event and then do something with it. Am I overcomplicating things, or is this doable?

Chasten answered 25/1, 2013 at 3:5 Comment(0)
P
11

You have to use a second constraint:

void DoMethod<TEvent, TArgs>() where TEvent : IEvent<TArgs> where TArgs : EventArgs {}
Pazit answered 25/1, 2013 at 3:9 Comment(0)
H
1

Try this.

public class IEvent<T> where T : EventArgs { }
public class EventManager
{
    public void DoMethod<T, U>() where T : IEvent<U> where U : EventArgs
    {
    }
}
Hedonics answered 25/1, 2013 at 3:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.