Reputation: 3597
Is there any way at all to achieve the use of downstream delegate definitions in an abstract parent class?
Delegates, like types, can't be overridden:
public abstract class ActionIssuerSimple
{
public delegate void ActionHandler();
...
public void Subscribe(ActionHandler handler) { ... }
}
public abstract class ActionIssuer<TAction> : ActionIssuerSimple
{
public override delegate void ActionHandler(TAction parameter);
...
}
The above gives the error "delegate cannot be override"
The goal is, given an example of SillyIssuer : ActionIssuer<SillyAction>
, for me to be able to use sillyIssuer.Subscribe((SillyAction action) => { ... });
(in addition to using ActionIssuerSimple for actions that can run handlers with the signature () => { }
. Because C# doesn't support using downstream Delegate definitions in an abstract class, neither through abstract
, generic type parameters, nor override
, I can't quite find a way to do this without either:
Upvotes: 5
Views: 6494
Reputation: 3990
The reason delegates cannot be overridden is seen in the compiled assembly:
.class auto ansi sealed nested public ActionHandler
extends [mscorlib]System.MulticastDelegate
{
} // end of class ActionHandler
You see, ActionHandler is not a 'real field' of the class - it's just a nested sealed class! :D
Upvotes: 3
Reputation: 73502
Not sure what you're trying to achieve. You can override a Property/Method not Types. Delegate is a type and what does it mean to override a delegate?
I guess you need a generic delegate which you can take as a parameter in ActionIssuer<TAction>.Subscribe
method.
public delegate void ActionHandler<TAction>(TAction parameter);
public abstract class ActionIssuer<TAction>
{
public void Subscribe(ActionHandler<TAction> handler) { ... }
...
}
Then you could do
sillyIssuer.Subscribe((SillyAction action) => { ... });
Upvotes: 1
Reputation: 17605
It would be possible to use the desired delegate type as a type parameter for ActionIssuer
turned into a generic class.
Upvotes: 2