Can a Delegate have an optional parameter?

2019-01-15 08:36发布

I have the below code that was working fine until I tried adding the bool NetworkAvailable = true portion. Now I get a Method name expected compile time exception at Line 4 below.

void NetworkStatus_AvailabilityChanged(object sender, NetworkStatusChangedArgs e)
{
   var networkAvailable = e.IsAvailable;
   SetUpdateHUDConnectedMode d = new SetUpdateHUDConnectedMode(UpdateHUDConnectedMode(networkAvailable));
   this.Invoke(d);
}   

delegate void SetUpdateHUDConnectedMode(bool NetworkAvailable = true);
private void UpdateHUDConnectedMode(bool NetworkAvailable = true)
{
   ...
}

I am, admittedly, new to Delegates and Optional Parameters so I would be grateful for any insight. Thanks.

2条回答
叛逆
2楼-- · 2019-01-15 08:56

A delegate points to a method definition.
When you instantiate a delegate pointing to a method, you cannot specify any parameters.

Instead, you need to pass the parameter values to the Invoke method, like this:

SetUpdateHUDConnectedMode d = UpdateHUDConnectedMode;
this.Invoke(d, e.IsAvailable);
查看更多
Fickle 薄情
3楼-- · 2019-01-15 09:16

To some very limited extent. Using C# 4 :

 public delegate void Test(int a, int b = 0);

 static void T1(int a, int b) { }
 static void T2(int a, int b = 0) { }
 static void T3(int a) { }


    Test t1 = T1;
    Test t2 = T2;
    Test t3 = T3;   // Error

And then you can call

    t1(1);
    t1(1, 2);
    t2(2);
    t2(2, 3);
查看更多
登录 后发表回答