myn*_*fey 18 c# asp.net-mvc lambda anonymous-function
为简单起见,请想象以下代码:
我想创建一个Foo:
public class Foo
{
public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并将其传递给特殊的Html Helper方法:
Html.SomeFunction(f => f.Bar);
Run Code Online (Sandbox Code Playgroud)
其定义为:
public string SomeFunction<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
Run Code Online (Sandbox Code Playgroud)
我想在这个函数中得到Bar的值,但是完全不知道如何得到它.
Tej*_*ejs 32
只需编译表达式并获取值.
Func<TModel, TValue> method = expression.Compile();
TValue value = method(html.ViewData.Model);
// might be a slightly different property, but you can get the ViewModel
// from the HtmlHelper object.
Run Code Online (Sandbox Code Playgroud)
您需要调用Compile()表达式来获取Func然后执行它.
public string SomeFunction<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
TValue valueOfBar = expression.Compile()(html.Model); // Assumes Model is accessible from html.
// Do stuff
}
Run Code Online (Sandbox Code Playgroud)
旁注:如果不需要动态表达式或表达式分析,您也可以直接传递Func.
对于那些使用没有 MVT 模型的表达式的人,可以通过以下方式获取属性的名称和值。
public static string Meth<T>(Expression<Func<T>> expression)
{
var name = ((MemberExpression)expression.Body).Member.Name;
var value = expression.Compile()();
return string.Format("{0} - {1}", name, value);
}
Run Code Online (Sandbox Code Playgroud)
使用:
Meth(() => YourObject.Property);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10724 次 |
| 最近记录: |