I have a generic delegate that accepts a argument, Args<T>
. I also have a normal delegate which accepts Args
.
delegate Task ExampleDelegate<T>(Args<T> args)
delegate Task ExampleDelegate(Args args)
Args<T>
extends from Args
public class Args {
}
public class Args<T> : Args {
}
I am currently extending my non generic interfaces/classes which use ExampleDelegate
to create new generic interfaces/classes using ExampleDelegate<T>
.
Since all of them extend the non-generic versions, it has been painless to extend them so far until I had to override a method which accepts ExampleDelegate
.
I haven't been able to cast ExampleDelegate<T>
into ExampleDelegate
since the signatures don't match.
One of the ways I was able to this was,
ExampleDelegate<SomeClass> genericDelegate= //some method
//First case
ExampleDelegate nonGenericDelegate = args => genericDelegate(args as Args<SomeClass>);
//Second case
genericDelegate = argsT => nonGenericDelegate(argsT);
Is there any better way of doing this?
Update: Is it possible to do this without creating an anonymous method like the one above?
CodePudding user response:
Is there any better way of doing this?
Probably yes, but we don't know what you are trying to do so we can't help you
I don't see why I need to cast explicitly in the second case as well?
You don't...? Here is some code that compiles just fine:
class TestClass
{
void DoStuff()
{
ExampleDelegate nonGeneric = a => { };
ExampleDelegate<int> generic = b => nonGeneric(b);
}
}
delegate void ExampleDelegate(Args args);
delegate void ExampleDelegate<T>(Args<T> args);
class Args<T> : Args {}
class Args {}