【发布时间】:2011-07-15 13:08:15
【问题描述】:
我正在尝试使用 Lambda 表达式和反射来获取成员分层名称(而不是使用文本常量),以在我的控件绑定信息无效时强制执行编译时错误。
这是在 ASP.NET MVC 项目中,但它不是特定于 MVC 的问题 AFAIK。编辑:具体来说,我希望以下评估为真:
string fullname = GetExpressionText(model => model.Locations.PreferredAreas);
"Locations.PreferredAreas" == fullname;
我得到一个编译错误:
错误 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);
这是来自 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...
【问题讨论】:
-
你忘了包括你的问题最相关的部分——GetExpressionText 源代码:)
-
没关系,它是一个 MVC 助手。看我的回答。
-
这真的相关吗?基于 Eric Lippert 的回答(他回答的内容,而不仅仅是他能够回答的事实)GetExpressionText 背后的来源不相关,对吧?
-
你还记得你最终做了什么吗?那个代表埃里克在说什么?
-
查看下面的另一个答案以获得代码示例,Lum。
标签: c# asp.net-mvc linq lambda