C # compiler error: cannot convert lambda expression

I am trying to use Lambda expression and reflection to get a hierarchical member name (instead of using a text constant) to force compile-time errors if my control binding information is invalid.

This is in an ASP.NET MVC project, but this is not an AFAIK MVC specific issue. EDIT: In particular, I want the following to evaluate to true:

string fullname = GetExpressionText(model => model.Locations.PreferredAreas); "Locations.PreferredAreas" == fullname; 

Instead, I get a compilation error:

Error 4: Unable to convert lambda expression to type 'System.Linq.Expressions.LambdaExpression' because it is not a delegate type.

Why does the parameter work in the second case below, but not the first?

 // 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); 

Here is the relevant code from the ASP.NET MVC Codeplex project. It seems to me that it passes the same parameter to the same method:

 // 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... 
+4
source share
4 answers

The error message is correct. A lambda can be converted to a compatible delegate type, D, or to an expression-compatible-delegate type Expression<D> . Expression<Func<TM, TP>> is one such. "LambdaExpression" is neither one nor the other. Therefore, you get an error trying to convert lambda to LambdaExpression, but not to the type of the actual expression tree. There must be a delegate.

+13
source

I think you should try using a helper method:

 public static string GetExpressionText<M, P>(this M model, Expression<Func<M, P>> ex) { return GetExpressionText(ex); } 
+2
source

Before attempting to fix lambda expressions, make sure that the following links are already added:

System.Linq;
System.Linq.Expressions;

The absence of these links may also cause the same error ("Cannot convert lambda expression to type" System.Linq.Expressions.Lambda Expression "because it is not a delegate type").

Hope this helps ...

+2
source

A post detailing the specific use of expressions: http://blog.joefield.co.uk/?m=201004

0
source

Source: https://habr.com/ru/post/1343723/


All Articles