Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.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# 是否可以让指向函数的委托具有;预设;论据_C#_Delegates - Fatal编程技术网

C# 是否可以让指向函数的委托具有;预设;论据

C# 是否可以让指向函数的委托具有;预设;论据,c#,delegates,C#,Delegates,C#的新成员。是否可以让委托指向具有我设置的“预设”参数的函数 public delegate void Del(string message); static void Notify(string name) { Console.WriteLine("Notification received for: {0}", name); } // Looking for something similar, but code below gives me an error // Del

C#的新成员。是否可以让委托指向具有我设置的“预设”参数的函数

public delegate void Del(string message);
static void Notify(string name)
{
     Console.WriteLine("Notification received for: {0}", name);
}

// Looking for something similar, but code below gives me an error 
// Del del5 = Notify("http://stackoverflow.com");  

不,这样做是不可能的,因为这将把Notify方法调用的结果(void)分配给del5。代理不允许使用默认参数值。

当然-您可以使用lambda调用该函数,并使用您想要的任何参数。在您的情况下,我们似乎完全忽略了参数,按照惯例,该参数被写为
作为参数名称:

Del del5 = _ => Notify("http://stackoverflow.com");  
del5("whatever - ignored anyway"); // always calls Notify("http://stackoverflow.com")
更一般的情况是,函数具有多个(即2个)参数,而不是在委托中指定第一个为固定值:

static void Notify2(string siteName, string message) {...}
Del messageToStackOverflow = message => 
      Notify2 ("http://stackoverflow.com", message);

// calls Notify2 adding first argument SO: 
// Notify2("http://stackoverflow.com", "Useful message to SO")
messageToStackOverflow("Useful message to SO");

通常,当您将某些参数固定到特定值时,会调用此函数。

@当然可以。旁注:不是每个人都能读俄语。请尽量用英语发表所有帖子/评论,因为大多数读者用其他语言发表的评论不可读,因此不清楚是赞扬、诅咒还是要求澄清。