我正在尝试使用 Lambda 表达式和反射来获取成员层次结构名称(而不是使用文本常量),以在我的控件绑定(bind)信息无效时强制执行编译时错误。
这是在 ASP.NET MVC 项目中,但它不是特定于 MVC 的问题 AFAIK。编辑:具体来说,我希望以下评估为真:
string fullname = GetExpressionText(model => model.Locations.PreferredAreas);
"Locations.PreferredAreas" == fullname;
相反,我得到一个编译错误:
Error 4: Cannot convert lambda expression to type 'System.Linq.Expressions.LambdaExpression' because it is not a delegate type.
为什么参数在下面的第二种情况下起作用,而第一种情况下不起作用?
// 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...
最佳答案
错误信息是正确的。 lambda 可以转换为兼容的委托(delegate)类型 D,或转换为兼容委托(delegate)类型的表达式 Expression<D>
. Expression<Func<TM, TP>>
是其中之一。 “LambdaExpression”两者都不是。因此,您在尝试将 lambda 转换为 LambdaExpression 而不是实际的表达式树类型时会出错。在某处必须有一个代表。
关于C# 编译器错误 : Cannot convert lambda expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5308017/