.net defines a function that accepts a lambda expression

I want to define a function, such as the function of the MVC TextBoxFor extension template

The interesting thing for this function is that I do not need to specify the TProperty type. How can I set this in my function definition.

My code looks like this:

public class Helper<TItem>
{
    public string GetMemberName(Expression<Func<TItem, TProperty>> expression)
    {
        ... returns TProperty.Name

    }
}

The actual problem is that this does not compile ... because it cannot find the TProperty type.

As a result, I want to define a class once with a type ... and then use the GetMemberName function to get the name of each member, as in the MVCframework.

Helper<Employee> h = new Helper<Employee>();
string name = h.GetMemberName(e=>e.Name);
....

I do not want me to be forced to specify the type of TProperty when writing code. In principle, it can be any object.

Thank,

Radu

+3
4

, :

public class Helper<TItem>
{
    public string GetMemberName<TProperty>(Expression<Func<TItem, TProperty>> expression)
    {
        return string.Empty; // I didn't implement it
    }
}

<TProperty> , . TProperty , , :

Helper<Employee> h = new Helper<Employee>();
h.GetMemberName( e=>e.Name); //if Employee has such a property
+3

, :

    public static string Property<T>(Expression<Func<T>> e)
    {
        var member = (MemberExpression)e.Body;
        return member.Member.Name;
    }
+1

ModelMetaData Expression.

public string GetMemberName<TProperty>(Expression<Func<TItem, TProperty>> expression) {
   var meta = ModelMetaData.FromLambdaExpression(expression, null);
   return meta.PropertyName; // Or something else
}
0

, . Func<T, object>, MemberExpression

, UnaryExpression, MemberExpression , .

QuickWatch . , HtmlHelper MVC .

EDIT:

, ( , , ), Employee , .

, :

public static class Helper
{
    public static string Item<TItem,TMember>(this TItem obj, Expression<Func<TItem, TMember>> expression)
    {
        if (expression.Body is MemberExpression)
        {
            return ((MemberExpression)(expression.Body)).Member.Name;
        }
        if(expression.Body is UnaryExpression)
        {
            return ((MemberExpression)((UnaryExpression)(expression.Body)).Operand).Member.Name;
        }
        throw new InvalidOperationException();
    }
}

,

Employee emp = new Employee();
emp.Item(o=>o.Name);

,

0

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


All Articles