LambdaExpression constructor

I saw the code as shown below. My questions:

1> ()=>Name

What does this mean?

2> Is Expression<Func<>>

the same as Expression<TDelegate>

? How ()=>Name

is the difference Expression<Func<>>

and which constructor is used? Most expression classes do not have common constructors. How does the C # compiler convert from Lambda to expression?

3> What is the cost of executing the Parse function?

public class Test
{
    public string Name {get;set;}

    public void Start()
    {
        Parse(()=>Name);
    }

    public string Parse<T>(Expression<Func<T>> exp)
    {
        var mexp = (System.Linq.Expressions.MemberExpression)expression.Body;
        return mexp == null ? "" : mexp.Member.Name;
    }
}

      

+3


source to share


2 answers


  • It is a lambda that takes no arguments but results in String

    .
  • Not. TDelegate

    is a template argument. Func<T>

    is a concrete type that satisfies the constraints TDelegate

    . The C # compiler converts the lambda to the appropriate type at compile time.
  • You have to measure in order to answer this question.


+5


source


So, ()=>Name

is a lambda function. This is a function that returns a property Name

. In your case, this thing is Func<string>

by type.

This all changes a bit because you are passing it to a field that is defined as Expression<Func<T>>

. In your case, you give Expression<Func<string>>

. It basically makes a lambda function an expression of a lambda function, which gives you not the result of the function but a structure.



Typically, this structure is used to safely define a property name. For example, to prevent confusion or accidental renaming with your code.

+3


source







All Articles