2016-02-26 54 views
4

我有一個簡單的問題,可能很容易answerd而是大量使用谷歌並沒有彈出一個回答我的問題。所以我很抱歉,如果有正確的解決方案,我沒有看到它。功能的方法調用的參數

如果我有一個像

Object.Add(string text, System.Drawing.Color color); 

,它是將一些文本的一些對象與指定顏色的方法調用,我想動態改變顏色,那麼我可以鍵入某事。像

Object.Add("I'm a string", SomeBool ? Color.Red : Color.Green); 

這是非常有幫助的,但只要我想比較不僅僅是兩種情況,就會失敗。

我正在尋找的是類似的信息(僞)

Object.Add("I'm another string", new delegate (Sytem.Drawing.Color) 
{ 
    if (tristate == state.state1) 
    { 
     return Color.Blue; 
    } 
    else if (tristate == state2) 
    { 
     return Color.Green; 
    } 
    // ... 
}); 

但不管如何我想它會拋出一個編譯器錯誤。

我嘗試瞭如何將一個函數作爲方法參數,但我會發現,很多像​​

public void SomeFunction(Func<string, int> somefunction) 
{ 
    //... 
} 

這是不是我的問題很多谷歌的。

謝謝:)

回答

1

我建議使用字典,例如

private static Dictionary<State, Color> s_Colors = new Dictionary<State, Color>() { 
    {State1, Color.Blue}, 
    {State2, Color.Green}, 
    {State3, Color.Red}, 
    }; 


    ... 

    Object.Add("I'm a string", s_Colors[tristate]); 
+0

非常好的解決方案。喜歡它 :) – AllDayPiano

5

只是第一把你的邏輯:

Color color; 

if (tristate == state1) 
    color = Color.Blue; 
else if (tristate == state2) 
    color = Color.Green; 
else 
    color = Color.Red; 

Object.Add("I'm a string", color); 

的原因,你的delegate解決方案沒有工作很簡單,就是new delegate (Sytem.Drawing.Color) { … }返回一個函數委託其需要先叫你之前一個顏色值。而且,由於你的方法需要一種顏色,而不是返回的顏色的方法,它是不是真的有幫助。

根據您的邏輯多麼短暫你仍然可以在這裏使用三元條件運算符和簡單的IT連鎖:

Object.Add("I'm a string", tristate == state1 ? Color.Blue : tristate == state2 ? Color.Green : Color.Red); 

這相當於上面詳細if/else if/else結構。但是,當然,它不一定是更具有可讀性,謹慎所以使用和選擇更可讀的解決方案。

+0

哦,適合什麼,我在什麼地方閱讀有關委託。從邏輯上講,委託人無法工作。 – AllDayPiano

1

這將讓你通過一個函數來決定國家和色彩傳遞到一個動作,你可以再決定該怎麼做。實際上,文本和顏色只能在Add方法內部使用,並且根本不需要返回使用,但這只是看起來您正在尋找的一個示例。因爲你不使用Add方法內的文本(在你的榜樣任何方式),我把它和它正好可以在行動中使用,否則只是重新添加它並使用它的Add方法裏面。

void Main() 
{ 
    Object.Add(() => SomeState.State2, (col) => 
    { 
     Label1.Text = "Your text"; 
     //Do something with color 
     Label1.BackColor = col; 
    }); 

    //example 2 
    Object.Add(() => 
     { 
      return someBool ? SomeState.State1 : SomeState.State2; 
     }, 
     (col) => 
     { 
      Label1.Text = "Your text"; 
      //Do something with color 
      Label1.BackColor = col; 
     }); 
} 

public static class Object 
{ 
    public static void Add(Func<SomeState> func, Action<Color> action) 
    { 
     switch(func()) 
     { 
      case SomeState.State1: 
       action(Color.Blue); 
       break; 
      case SomeState.State2: 
       action(Color.Green); 
       break; 
      default: 
       action(Color.Black); 
       break; 
     } 
    } 
} 

public enum SomeState 
{ 
    State1, 
    State2 
}