Convert Func to Delegate [duplicate]

2019-06-16 02:18发布

This question already has an answer here:

I have the following delegate defined:

public delegate object MyDelegate(dynamic target);

And I have a Func<dynamic, object> object:

Func<dynamic, object> myFunc

How can I convert myFunc to MyDelegate?

I have tried these instructions, none of them worked:

MyDelegate myDeleg = myFunc;
MyDelegate myDeleg = (MyDelegate) myFunc;
MyDelegate myDeleg = myFunc as MyDelegate;

1条回答
老娘就宠你
2楼-- · 2019-06-16 02:34

You can wrap the existing delegate:

(MyDelegate)(x => myFunc(x))

Or equivalently:

MyDelegate myDeleg = x => myFunc(x);

This causes a small performance loss on each invocation but the code is very simple.

查看更多
登录 后发表回答