2013-10-25 18 views
0

我有一個目前看起來像這樣一類:如何採取一個可選的參數行動<T1,T2>

public Action<string> Callback { get; set; } 

public void function(string, Action<string> callback =null) 
{ 
    if (callback != null) this.Callback = callback; 
    //do something 
} 

現在我想的是把像一個可選的參數:

public Action<optional, string> Callback { get; set; } 

我試着:

public Action<int optional = 0, string> Callback { get; set; } 

它不起作用。

有沒有什麼辦法可以讓Action<...>帶一個可選參數?

+2

http://stackoverflow.com/questions/7690482/parameter-actiont1-t2-t3-in-which-t3-can-be-optional – Habib

+0

這個語法不太可能存在。以及返回值中的可選參數究竟如何工作? – Zong

回答

2

你不能用一個System.Action<T1, T2>做到這一點,但你可以定義自己的委託類型是這樣的:

delegate void CustomAction(string str, int optional = 0); 

,然後用它是這樣的:

CustomAction action = (x, y) => Console.WriteLine(x, y); 
action("optional = {0}"); // optional = 0 
action("optional = {0}", 1); // optional = 1 

注意的幾件事關於這一點,雖然。

  1. 就像在普通的方法中,所需的參數不能在可選參數之後出現,所以我必須在這裏顛倒參數的順序。
  2. 默認值是在您定義委託人而不是您聲明變量實例的位置時指定的。
  3. 你能做出這樣的委託通用的,但最有可能的,你只能夠使用default(T2)爲默認值,就像這樣:

    delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2)); 
    CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y); 
    
相關問題