问题
What is the best way to convert from a delegate that takes a first parameter of a derived type into one that receives a base type? What I mean is:
Func<DerivedType, Object> original = ...;
Func<BaseType, Object> converted = Something(original);
Casts, of course, do not work, since these are actually two different types.
回答1:
Since you want to pass a base type to a method that takes a derived type, you need to add a cast. If you know that all calls to converted
would be passing DerivedType
, you could make a straightforward wrapper, like this:
Func<BaseType,Object> converted = b => original((DerivedType)b);
Demo.
来源:https://stackoverflow.com/questions/31410342/convert-funcderivedtype-object-to-funcbasetype-object