Convert Func to Delegate [duplicate]

2019-06-16 01:59发布

问题:

This question already has an answer here:

  • Cast delegate to Func in C# 8 answers

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:

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.