"dynamic" for anonymous delegates?

I wonder if it is possible to make the "dynamic" type for variables work for anonymous delegates.

I tried the following:

dynamic v = delegate() { }; 

But then I got the following error message:

Cannot convert anonymous method to type 'dynamic' because it is not a delegate type

Unfortunately, the following code does not work:

 Delegate v = delegate() { }; object v2 = delegate() { }; 

What if I want to create a method that accepts any type of delegate, even built-in declared ones?

For instance:

 class X{ public void Y(dynamic d){ } static void Main(){ Y(delegate(){}); Y(delegate(string x){}); } } 
+4
source share
3 answers

It works, but it looks a bit strange. You can give it any delegate, it will run it and also return the value.

You also need to specify the signature of the anonymous method at some point so that the compiler can understand it, so you need to specify Action<T> or Func<T> or something else.

Why can't you assign an anonymous method to var?

  static void Main(string[] args) { Action d = () => Console.WriteLine("Hi"); Execute(d); // Prints "Hi" Action<string> d2 = (s) => Console.WriteLine(s); Execute(d2, "Lo"); // Prints "Lo" Func<string, string> d3 = (s) => { Console.WriteLine(s); return "Done"; }; var result = (string)Execute(d3, "Spaghettio"); // Prints "Spaghettio" Console.WriteLine(result); // Prints "Done" Console.Read(); } static object Execute(Delegate d, params object[] args) { return d.DynamicInvoke(args); } 
+5
source

If you declare a type for each of your delegates, it works.

 // Declare it somewhere delegate void DelegateType(string s); // The cast is required to make the code compile Test((DelegateType)((string s) => { MessageBox.Show(s); })); public static void Test(dynamic dynDelegate) { dynDelegate("hello"); } 
+1
source
 Action _; dynamic test = (_ = () => Console.WriteLine("Test")); test() // Test 
0
source

Source: https://habr.com/ru/post/1414146/


All Articles