Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MethodInvoker的正确语法是什么?_C#_Invoke - Fatal编程技术网

C# MethodInvoker的正确语法是什么?

C# MethodInvoker的正确语法是什么?,c#,invoke,C#,Invoke,下面的代码编译并运行良好 void myInvokedMethod(string s) { Console.WriteLine(s); } void myInvoker() { Invoke(new MethodInvoker(delegate() { myInvokedMethod("one"); })); Invoke(new MethodInvoker(delegate { myInvokedMethod("two"); })); } 当我调用myInvok

下面的代码编译并运行良好

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

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

当我调用myInvoker时,对myInvokedMethod的两个调用都能通过。delegate后面的括号是什么意思?为什么它们看起来是可选的?

它们指定了需要的形式参数,如果不需要,则是可选的。如果在没有参数列表的情况下声明,则可以将其分配给具有参数的委托类型。

括号称为匿名方法参数列表,在本例中为空。匿名方法没有类型-编译器尝试执行隐式转换。如果给出匿名方法的签名,则该签名必须与委托的签名匹配

如果以下所有条件均成立,也可以进行隐式转换:

  • 省略委托的形式参数列表
  • 委托没有out参数
  • 返回类型匹配
第二个例子就是这样。因此,这两条线之间没有区别——它们都做相同的事情。下面是另一个例子:

var x1 = new ParameterizedThreadStart(delegate(object o) {}); // Compiles.
var x2 = new ParameterizedThreadStart(delegate {});           // Compiles.
var x3 = new ParameterizedThreadStart(delegate() {});         // Does not compile.
最后两个示例表明,
delegate(){}
delegate{}
通常是不等价的。它们仅在您的情况下是等效的,因为不需要任何参数。有关更多详细信息和示例,请参见C#规范第21节