Retrieving Property name from lambda expression

前端 未结 21 1704
迷失自我
迷失自我 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:59

    static void Main(string[] args)
    {
        var prop = GetPropertyInfo(_ => _.MyProperty);
    
        MyDto dto = new MyDto();
        dto.MyProperty = 666;
    
        var value = prop.GetValue(dto);
        // value == 666
    }
    
    class MyDto
    {
        public int MyProperty { get; set; }
    }
    
    public static PropertyInfo GetPropertyInfo(Expression> propertyLambda)
    {
        Type type = typeof(TSource);
    
        var member = propertyLambda.Body as MemberExpression;
        if (member == null)
        {
            var unary = propertyLambda.Body as UnaryExpression;
            if (unary != null)
            {
                member = unary.Operand as MemberExpression;
            }
        }
        if (member == null)
        {
            throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));
        }
    
        var 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("Expression '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(), type));
        }
    
        return propInfo;
    }
    

提交回复
热议问题