What is the correct syntax for using MethodInvoker?

The following code compiles and works fine.

void myInvokedMethod(string s)
{
    Console.WriteLine(s);
}

void myInvoker()
{
    Invoke(new MethodInvoker(delegate() { myInvokedMethod("one"); }));
    Invoke(new MethodInvoker(delegate   { myInvokedMethod("two"); }));
}

When I call myInvoker , both myInvokedMethod calls go through. What do parentheses after delegate mean and why do they seem optional?

+3
source share
2 answers

The brackets are called the parameter list of the anonymous method and in this case is empty. An anonymous method has no type - the compiler is trying to perform an implicit conversion. If an anonymous method is signed, it must match the signature of the delegate.

Implicit conversion is also possible if the following is true:

. , - . :

var x1 = new ParameterizedThreadStart(delegate(object o) {}); // Compiles.
var x2 = new ParameterizedThreadStart(delegate {});           // Compiles.
var x3 = new ParameterizedThreadStart(delegate() {});         // Does not compile.

, delegate(){} delegate{} . , MethodInvoker . . 21 # .

+3

, , . , , .

+3
source

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


All Articles