Retrieving Property name from lambda expression

前端 未结 21 1762
迷失自我
迷失自我 2020-11-21 11:12

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

eg.

GetSortingInfo         


        
21条回答
  •  青春惊慌失措
    2020-11-21 11:51

    Here's an update to method proposed by Cameron. The first parameter is not required.

    public PropertyInfo GetPropertyInfo(
        Expression> propertyLambda)
    {
        Type type = typeof(TSource);
    
        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));
    
        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));
    
        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));
    
        return propInfo;
    }
    

    You can do the following:

    var propertyInfo = GetPropertyInfo(u => u.UserID);
    var propertyInfo = GetPropertyInfo((SomeType u) => u.UserID);
    

    Extension methods:

    public static PropertyInfo GetPropertyInfo(this TSource source,
        Expression> propertyLambda) where TSource : class
    {
        return GetPropertyInfo(propertyLambda);
    }
    
    public static string NameOfProperty(this TSource source,
        Expression> propertyLambda) where TSource : class
    {
        PropertyInfo prodInfo = GetPropertyInfo(propertyLambda);
        return prodInfo.Name;
    }
    

    You can:

    SomeType someInstance = null;
    string propName = someInstance.NameOfProperty(i => i.Length);
    PropertyInfo propInfo = someInstance.GetPropertyInfo(i => i.Length);
    

提交回复
热议问题