Retrieving Property name from lambda expression

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

    I"m using an extension method for pre C# 6 projects and the nameof() for those targeting C# 6.

    public static class MiscExtentions
    {
        public static string NameOf(this object @object, Expression> propertyExpression)
        {
            var expression = propertyExpression.Body as MemberExpression;
            if (expression == null)
            {
                throw new ArgumentException("Expression is not a property.");
            }
    
            return expression.Member.Name;
        }
    }
    

    And i call it like:

    public class MyClass 
    {
        public int Property1 { get; set; }
        public string Property2 { get; set; }
        public int[] Property3 { get; set; }
        public Subclass Property4 { get; set; }
        public Subclass[] Property5 { get; set; }
    }
    
    public class Subclass
    {
        public int PropertyA { get; set; }
        public string PropertyB { get; set; }
    }
    
    // result is Property1
    this.NameOf((MyClass o) => o.Property1);
    // result is Property2
    this.NameOf((MyClass o) => o.Property2);
    // result is Property3
    this.NameOf((MyClass o) => o.Property3);
    // result is Property4
    this.NameOf((MyClass o) => o.Property4);
    // result is PropertyB
    this.NameOf((MyClass o) => o.Property4.PropertyB);
    // result is Property5
    this.NameOf((MyClass o) => o.Property5);
    

    It works fine with both fields and properties.

提交回复
热议问题