Retrieving Property name from lambda expression

前端 未结 21 1696
迷失自我
迷失自我 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 12:04

    This is a general implementation to get the string name of fields/properties/indexers/methods/extension methods/delegates of struct/class/interface/delegate/array. I have tested with combinations of static/instance and non-generic/generic variants.

    //involves recursion
    public static string GetMemberName(this LambdaExpression memberSelector)
    {
        Func<Expression, string> nameSelector = null;  //recursive func
        nameSelector = e => //or move the entire thing to a separate recursive method
        {
            switch (e.NodeType)
            {
                case ExpressionType.Parameter:
                    return ((ParameterExpression)e).Name;
                case ExpressionType.MemberAccess:
                    return ((MemberExpression)e).Member.Name;
                case ExpressionType.Call:
                    return ((MethodCallExpression)e).Method.Name;
                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                    return nameSelector(((UnaryExpression)e).Operand);
                case ExpressionType.Invoke:
                    return nameSelector(((InvocationExpression)e).Expression);
                case ExpressionType.ArrayLength:
                    return "Length";
                default:
                    throw new Exception("not a proper member selector");
            }
        };
    
        return nameSelector(memberSelector.Body);
    }
    

    This thing can be written in a simple while loop too:

    //iteration based
    public static string GetMemberName(this LambdaExpression memberSelector)
    {
        var currentExpression = memberSelector.Body;
    
        while (true)
        {
            switch (currentExpression.NodeType)
            {
                case ExpressionType.Parameter:
                    return ((ParameterExpression)currentExpression).Name;
                case ExpressionType.MemberAccess:
                    return ((MemberExpression)currentExpression).Member.Name;
                case ExpressionType.Call:
                    return ((MethodCallExpression)currentExpression).Method.Name;
                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                    currentExpression = ((UnaryExpression)currentExpression).Operand;
                    break;
                case ExpressionType.Invoke:
                    currentExpression = ((InvocationExpression)currentExpression).Expression;
                    break;
                case ExpressionType.ArrayLength:
                    return "Length";
                default:
                    throw new Exception("not a proper member selector");
            }
        }
    }
    

    I like the recursive approach, though the second one might be easier to read. One can call it like:

    someExpr = x => x.Property.ExtensionMethod()[0]; //or
    someExpr = x => Static.Method().Field; //or
    someExpr = x => VoidMethod(); //or
    someExpr = () => localVariable; //or
    someExpr = x => x; //or
    someExpr = x => (Type)x; //or
    someExpr = () => Array[0].Delegate(null); //etc
    
    string name = someExpr.GetMemberName();
    

    to print the last member.

    Note:

    1. In case of chained expressions like A.B.C, "C" is returned.

    2. This doesn't work with consts, array indexers or enums (impossible to cover all cases).

    0 讨论(0)
  • 2020-11-21 12:04

    I have done the INotifyPropertyChanged implementation similar to the method below. Here the properties are stored in a dictionary in the base class shown below. It is of course not always desirable to use inheritance, but for view models I think it is acceptable and gives very clean property references in the view model classes.

    public class PhotoDetailsViewModel
        : PropertyChangedNotifierBase<PhotoDetailsViewModel>
    {
        public bool IsLoading
        {
            get { return GetValue(x => x.IsLoading); }
            set { SetPropertyValue(x => x.IsLoading, value); }
        }
    
        public string PendingOperation
        {
            get { return GetValue(x => x.PendingOperation); }
            set { SetPropertyValue(x => x.PendingOperation, value); }
        }
    
        public PhotoViewModel Photo
        {
            get { return GetValue(x => x.Photo); }
            set { SetPropertyValue(x => x.Photo, value); }
        }
    }
    

    The somewhat more complex base class is shown below. It handles the translation from lambda expression to property name. Note that the properties are really pseudo properties since only the names are used. But it will appear transparent to the view model and references to the properties on the view model.

    public class PropertyChangedNotifierBase<T> : INotifyPropertyChanged
    {
        readonly Dictionary<string, object> _properties = new Dictionary<string, object>();
    
        protected U GetValue<U>(Expression<Func<T, U>> property)
        {
            var propertyName = GetPropertyName(property);
    
            return GetValue<U>(propertyName);
        }
    
        private U GetValue<U>(string propertyName)
        {
            object value;
    
            if (!_properties.TryGetValue(propertyName, out value))
            {
                return default(U);
            }
    
            return (U)value;
        }
    
        protected void SetPropertyValue<U>(Expression<Func<T, U>> property, U value)
        {
            var propertyName = GetPropertyName(property);
    
            var oldValue = GetValue<U>(propertyName);
    
            if (Object.ReferenceEquals(oldValue, value))
            {
                return;
            }
            _properties[propertyName] = value;
    
            RaisePropertyChangedEvent(propertyName);
        }
    
        protected void RaisePropertyChangedEvent<U>(Expression<Func<T, U>> property)
        {
            var name = GetPropertyName(property);
            RaisePropertyChangedEvent(name);
        }
    
        protected void RaisePropertyChangedEvent(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        private static string GetPropertyName<U>(Expression<Func<T, U>> property)
        {
            if (property == null)
            {
                throw new NullReferenceException("property");
            }
    
            var lambda = property as LambdaExpression;
    
            var memberAssignment = (MemberExpression) lambda.Body;
            return memberAssignment.Member.Name;
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    }
    
    0 讨论(0)
  • 2020-11-21 12:05

    Here is another way to get the PropertyInfo based off this answer. It eliminates the need for an object instance.

    /// <summary>
    /// Get metadata of property referenced by expression. Type constrained.
    /// </summary>
    public static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
    {
        return GetPropertyInfo((LambdaExpression) propertyLambda);
    }
    
    /// <summary>
    /// Get metadata of property referenced by expression.
    /// </summary>
    public static PropertyInfo GetPropertyInfo(LambdaExpression propertyLambda)
    {
        // https://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression
        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(propertyLambda.Parameters.Count() == 0)
            throw new ArgumentException(String.Format(
                "Expression '{0}' does not have any parameters. A property expression needs to have at least 1 parameter.",
                propertyLambda.ToString()));
    
        var type = propertyLambda.Parameters[0].Type;
        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;
    }
    

    It can be called like so:

    var propertyInfo = GetPropertyInfo((User u) => u.UserID);
    
    0 讨论(0)
提交回复
热议问题