功能的方法调用的参数

问题描述:

我有一个简单的问题,可能很容易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) 
{ 
    //... 
} 

这是不是我的问题很多谷歌的。

谢谢:)

我建议使用字典,例如

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

只是第一把你的逻辑:

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

这将让你通过一个函数来决定国家和色彩传递到一个动作,你可以再决定该怎么做。实际上,文本和颜色只能在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 
}