I believe this is not possible, think of the following case:
class Base { } class DerivedA : Base { } class DerivedB : Base { }
Using some methods:
string DoSomething(DerivedA myDerived) { }
Then you have the code:
Func<DerivedA, string> functionA = DoSomething; // Let assume this cast is possible... Func<Base, string> functionBase = (Func<BaseB, string>) functionA; // At this point, the signature of the function that functionBase is assigned to // is actually `string DoSomething(DerivedA myDerived)` functionB(new DerivedB()); // If the cast is allowed, then passing a DerivedB should be allowed, but this makes // absolutely no sense because the function is expecting a DerivedA.
What you can do is use the utility function to convert using the cast operator (or as
if you want):
Func<Base, string> Convert<T>(Func<T, string> function) where T : Base { return x => function(x as T); }
And then do something like:
Func<DerivedA, string> functionA = DoSomething; Func<Base, string> functionBase = Convert(functionA);
source share