如何实现Action委托?

时间:2013-03-30 11:37:52

标签: c# linq

我有一个班级

    public class TextBoxConfig
    {
        public string Caption { get; set; }
        public string FieldName { get; set; }
        public int Width { get; set; }
        public string Name { get; set; }
    }

和另一个实用程序类,它具有一个接受TextBoxConfig作为参数的方法,如此

    public class Util
    {
      public static TextBox ApplySettings(TextBoxConfig  config)
      {
         //Doing something
      }
    }

一般情况下,我可以像这样调用Util class ApplySettings方法

    TextBoxConfig config  = new TextBoxConfig();
    config.Caption = "Name";
    config.FieldName = "UserName"
    config.Width = 20;
    config.Name = "txtName";

    TextBox txt = Util.ApplySettings(config);

但我想将参数传递给ApplySettings,就像这样

    TextBox txt = Util.ApplySettings(o =>
    {
        o.Caption = "Name";
        o.FieldName = "UserName"
        o.Width = 20;
        o.Name = "txtName";
    });              

请建议我怎么做..

2 个答案:

答案 0 :(得分:0)

与您的愿望不完全相同,但非常接近:

TextBox txt = Util.ApplySettings(new TextBoxConfig()
{
    Caption = "Name",
    FieldName = "UserName",
    Width = 20,
    Name = "txtName"
});

请注意每个设置后的逗号。请参阅http://msdn.microsoft.com/en-us/library/vstudio/bb397680.aspx

答案 1 :(得分:0)

好吧,支持自己:这是同样的事情,只是用lambda表达式强制执行。

TextBox txt = Util.ApplySettings(o =>
{
    o.Caption = "Name";
    o.FieldName = "UserName";
    o.Width = 20;
    o.Name = "txtName";
});

public class Util
{
    public static TextBox ApplySettings(TextBoxConfig config)
    {
        //Doing something
    }

    public static TextBox ApplySettings(Action<TextBoxConfig> modifier)
    {
        var config = new TextBoxConfig();
        modifier(config);

        return ApplySettings(config);            
    }
}

我必须在声明后添加一些分号。我更喜欢另一个答案。但我希望这能满足你对lambda表达的渴望。

相关问题