是否可以让代理指向具有“预设”参数的函数

时间:2014-01-12 22:49:33

标签: 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 del5 = Notify("http://stackoverflow.com");  

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

Del del5 = _ => Notify("http://stackoverflow.com");  
del5("whatever - ignored anyway"); // always calls Notify("http://stackoverflow.com")

更多genric案例是具有许多(即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");

通常,当您将某些参数修复为特定值时,这会调用partial function application