2011-05-31 34 views
0

考虑下面的代码:行动<T>问题

private static Dictionary<Type, Action<Control>> controlDefaults = new Dictionary<Type, Action<Control>>() 
    { 
     { typeof(TextBox), c => ((TextBox)c).Clear() } 
    }; 

我怎么会调用在这种情况下采取行动?这是从别处获取的代码片段,并且该字典将包含更多控件实例。这将用于将表单上的所有控件重置为默认值。

所以我会重复这样:

foreach (Control control in this.Controls) 
{ 
    // Invoke action for each control 
} 

我怎么会再调用从词典中适当行动,电流控制?

谢谢。

回答

3

你可以写

controlDefaults[control.GetType()](control); 

你也use a static generic class作为字典,并避免铸造:

static class ControlDefaults<T> where T : Control { 
    public static Action<T> Action { get; internal set; } 
} 

static void Populate() { 
    //This method should be called once, and should be in a different class 
    ControlDefaults<TextBox>.Action = c => c.Clear(); 
} 

但是,您将无法在循环中调用此方法,因为你需要在编译时知道类型。

+0

感谢。这是我错过了第一行结尾处的(控制)部分。 – 2011-05-31 14:46:51

+0

换句话说,你是从字典中提取委托,但你没有做任何事情。 – SLaks 2011-05-31 14:47:30

+0

是的,这是我无法弄清楚的。谢谢。 – 2011-05-31 14:59:53

2

您可以像调用函数一样调用它。

例如为:

Action<Foo> action = foo => foo.Bar(); 
action(f); 

所以你的情况:

foreach(Control control in this.Controls) 
{ 
    controlDefaults[control.GetType()](control); 
} 
2
foreach (Control control in this.Controls) 
{ 
    Action<Control> defaultAction = controlDefaults[control.GetType()]; 
    defaultAction(control); 

    // or just 
    controlDefaults[control.GetType()](control); 
}