Convert Func<DerivedType, Object> to Func<BaseType, Object>

别来无恙 提交于 2020-02-04 14:33:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!