【问题标题】:How extract parameters passed by delegate parameter如何提取委托参数传递的参数
【发布时间】:2015-08-11 07:32:42
【问题描述】:

我尝试在 MVC 中构建一个助手。我尝试像这样传递参数:

@Html.InputHandler(settings =>
{
    settings.Name = "Julio";
    settings.Mask = "000-000-000";
    settings.visible = false;
    settings.Label = true;
    settings.htmlAttributes = new { @class="form-control" }
})

我有下面的参数定义代码

public delegate void Action<in T>(T obj);

public class InputSettings : SettingsBase
{
    public string Name { get; set; }
    public bool Label { get; set; }
    public string Binding { get; set; }
    public bool visible { get; set; }
    public object htmlAttributes { get; set; }
    public string Mask { get; set; }
}

问题是我无法获取从助手传递的值

public static MvcHtmlString InputHandler(this HtmlHelper htmlHelper, Action<InputSettings> method)
    {
        var parameters = method. ???        
        return new MvcHtmlString("");
    }

谢谢!

【问题讨论】:

    标签: c# parameters delegates helpers


    【解决方案1】:

    为了检索正文(因为在您尝试检索它时它已经被编译并 JIT 进入一个完全不同的状态),您需要一个Expression&lt;Action&lt;T&gt;&gt;。但是,您不能将 lambda 语句体转换为表达式树。因此,最好将强类型对象作为 Func 传递并立即拉回结果。

    void Main()
    {
        InputHandler(() => new InputSettings {
            Name = "Test1",
            Mask = "test mask"
        }); 
    }
    
    public static MvcHtmlString InputHandler(this HtmlHelper htmlHelper, 
        Func<InputSettings> method)
    {
        var parameters = method();        
        return new MvcHtmlString("");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2015-07-07
      • 2021-10-23
      相关资源
      最近更新 更多