获取.NET 3.5中的Lambda表达式中使用的属性名称

时间:2010-07-16 23:37:32

标签: c# .net lambda

我有一个问题一直困扰着我一段时间,我找不到答案。

我需要获取Lambda表达式中引用的属性的名称。我会将lambda表达式提供给一个返回字符串的方法。例如,如果我有:

x => x.WeirdPropertyName

然后该方法将返回:

"WeirdPropertyName"

我已经读过它可以用表达式树来完成,但答案已经没有了。

感谢您的帮助

3 个答案:

答案 0 :(得分:28)

你走了:

string GetPropertyName<T>(Expression<Func<T>> property)
{
    var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
    if (propertyInfo == null)
    {
        throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
    }
    return propertyInfo.Name;
}

答案 1 :(得分:6)

我有一个非常全面的答案here

除了处理x => x.WeirdPropertyName之类的表达式外,它还可以处理“扩展”表达式,例如x => x.WeirdMember.WeirdPropertyName

以下是该答案的代码:

// code adjusted to prevent horizontal overflow
static string GetFullPropertyName<T, TProperty>
(Expression<Func<T, TProperty>> exp)
{
    MemberExpression memberExp;
    if (!TryFindMemberExpression(exp.Body, out memberExp))
        return string.Empty;

    var memberNames = new Stack<string>();
    do
    {
        memberNames.Push(memberExp.Member.Name);
    }
    while (TryFindMemberExpression(memberExp.Expression, out memberExp));

    return string.Join(".", memberNames.ToArray());
}

// code adjusted to prevent horizontal overflow
private static bool TryFindMemberExpression
(Expression exp, out MemberExpression memberExp)
{
    memberExp = exp as MemberExpression;
    if (memberExp != null)
    {
        // heyo! that was easy enough
        return true;
    }

    // if the compiler created an automatic conversion,
    // it'll look something like...
    // obj => Convert(obj.Property) [e.g., int -> object]
    // OR:
    // obj => ConvertChecked(obj.Property) [e.g., int -> long]
    // ...which are the cases checked in IsConversion
    if (IsConversion(exp) && exp is UnaryExpression)
    {
        memberExp = ((UnaryExpression)exp).Operand as MemberExpression;
        if (memberExp != null)
        {
            return true;
        }
    }

    return false;
}

private static bool IsConversion(Expression exp)
{
    return (
        exp.NodeType == ExpressionType.Convert ||
        exp.NodeType == ExpressionType.ConvertChecked
    );
}

答案 2 :(得分:-4)

我知道获取属性的字符串名称的唯一方法是通过反射。