sha*_*non 5 c# linq asp.net-mvc lambda
我正在尝试使用Lambda表达式和反射来获取成员层次结构名称(而不是使用文本常量),以在我的控件绑定信息无效时强制执行编译时错误.
这是在ASP.NET MVC项目中,但它不是MVC特定的问题AFAIK.编辑:具体来说,我希望以下评估为真:
string fullname = GetExpressionText(model => model.Locations.PreferredAreas);
"Locations.PreferredAreas" == fullname;
Run Code Online (Sandbox Code Playgroud)
相反,我得到一个编译错误:
错误4:无法将lambda表达式转换为类型'System.Linq.Expressions.LambdaExpression',因为它不是委托类型.
为什么参数在下面的第二种情况下工作,而不是第一种?
// This doesn't compile:
string tb1 = System.Web.Mvc.ExpressionHelper.
GetExpressionText(model => model.Locations.PreferredAreas);
// But this does:
MvcHtmlString tb2 =
Html.TextBoxFor(model => model.Locations.PreferredAreas);
Run Code Online (Sandbox Code Playgroud)
这是ASP.NET MVC Codeplex项目的相关代码.在我看来,它将相同的参数传递给相同的方法:
// MVC extension method
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return TextBoxHelper(
htmlHelper,
metadata,
metadata.Model,
ExpressionHelper.GetExpressionText(expression),
htmlAttributes);
}
// MVC utility method
public static string GetExpressionText(LambdaExpression expression) {
// Split apart the expression string for property/field accessors to create its name
// etc...
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 15
错误消息是正确的.lambda可以转换为兼容的委托类型D,或者转换为兼容表达式委托类型Expression<D>. Expression<Func<TM, TP>>就是其中之一."LambdaExpression"既不是那些.因此,尝试将lambda转换为LambdaExpression时会出错,但不会转换为实际的表达式树类型.那里必须有代表.