从 lambda 表达式中检索属性名称 [英] Retrieving Property name from lambda expression

查看:30
本文介绍了从 lambda 表达式中检索属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过 lambda 表达式传入时,是否有更好的方法来获取属性名称?这是我目前拥有的.

Is there a better way to get the Property name when passed in via a lambda expression? Here is what i currently have.

例如.

GetSortingInfo<User>(u => u.UserId);

仅当属性是字符串时,它才通过将其转换为成员表达式来工作.因为并非所有属性都是字符串,所以我必须使用对象,但它会为这些属性返回一元表达式.

It worked by casting it as a memberexpression only when the property was a string. because not all properties are strings i had to use object but then it would return a unaryexpression for those.

public static RouteValueDictionary GetInfo<T>(this HtmlHelper html, 
    Expression<Func<T, object>> action) where T : class
{
    var expression = GetMemberInfo(action);
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

private static MemberExpression GetMemberInfo(Expression method)
{
    LambdaExpression lambda = method as LambdaExpression;
    if (lambda == null)
        throw new ArgumentNullException("method");

    MemberExpression memberExpr = null;

    if (lambda.Body.NodeType == ExpressionType.Convert)
    {
        memberExpr = 
            ((UnaryExpression)lambda.Body).Operand as MemberExpression;
    }
    else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
    {
        memberExpr = lambda.Body as MemberExpression;
    }

    if (memberExpr == null)
        throw new ArgumentException("method");

    return memberExpr;
}

推荐答案

我发现另一种方法是强类型化源和属性并显式推断 lambda 的输入.不确定这是否是正确的术语,但结果如下.

I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.

public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class
{
    var expression = (MemberExpression)action.Body;
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

然后这样称呼它.

GetInfo((User u) => u.UserId);

瞧,它起作用了.

这篇关于从 lambda 表达式中检索属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆