如何提取委托参数传递的参数
How extract parameters passed by delegate parameter
我尝试在 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("");
}
谢谢!
为了检索正文(因为当您尝试检索它时,它已经被编译并通过 JIT 进入完全不同的状态),您需要一个 Expression<Action<T>>
。但是,您不能将 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("");
}
我尝试在 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("");
}
谢谢!
为了检索正文(因为当您尝试检索它时,它已经被编译并通过 JIT 进入完全不同的状态),您需要一个 Expression<Action<T>>
。但是,您不能将 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("");
}