Pass property itself to function as parameter in C#

后端 未结 7 1607
春和景丽
春和景丽 2020-12-12 19:25

I am looking for a method to pass property itself to a function. Not value of property. Function doesn\'t know in advance which property will be used for sorting. Simplest w

相关标签:
7条回答
  • 2020-12-12 19:36

    What I found missing from @MatthiasG's answer is how to get property value not just its name.

    public static string Meth<T>(Expression<Func<T>> expression)
    {
        var name = ((MemberExpression)expression.Body).Member.Name;
        var value = expression.Compile()();
        return string.Format("{0} - {1}", name, value);
    }
    

    use:

    Meth(() => YourObject.Property);
    
    0 讨论(0)
  • 2020-12-12 19:37

    You can use an lambda expression to pass property information:

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

    Usage:

    DoSomething(() => this.MyProperty);
    
    0 讨论(0)
  • 2020-12-12 19:43

    Just to add from the answers above. You can also do a simple flag for the order direction.

    public class Processor
    {
        public List<SortableItem> SortableItems { get; set; }
    
        public Processor()
        {
            SortableItems = new List<SortableItem>();
            SortableItems.Add(new SortableItem { PropA = "b" });
            SortableItems.Add(new SortableItem { PropA = "a" });
            SortableItems.Add(new SortableItem { PropA = "c" });
        }
    
        public void SortItems(Func<SortableItem, IComparable> keySelector, bool isAscending)
        {
            if(isAscending)
                SortableItems = SortableItems.OrderBy(keySelector).ToList();
            else
                SortableItems = SortableItems.OrderByDescending(keySelector).ToList();
        }
    }
    
    0 讨论(0)
  • 2020-12-12 19:50

    I would like to give a simple, easy to understand answer.

    Function's parameter is this: System.Func<class, type of the property>

    And we pass the Property like this: Function(x => x.Property);

    Here is the code:

    class HDNData
    {
        private int m_myInt;
        
        public int MyInt
        {
            get { return m_myInt; }
        }
        
        public void ChangeHDNData()
        {
            if (m_myInt == 0)
                m_myInt = 69;
            else
                m_myInt = 0;
        }
    }
    
    static class HDNTest
    {
        private static HDNData m_data = new HDNData();
        
        public static void ChangeHDNData()
        {
            m_data.ChangeHDNData();
        }
        
        public static void HDNPrint(System.Func<HDNData, int> dataProperty)
        {
            Console.WriteLine(dataProperty(m_data));//Print to console the dataProperty (type int) of m_data
        }
    }
    
    //******Usage******
    HDNTest.ChangeHDNData();
    //This is what you want: Pass property itself (which is MyInt) to function as parameter in C#
    HDNTest.HDNPrint(x => x.MyInt);
    
    0 讨论(0)
  • 2020-12-12 19:54

    Why don't you use Linq for this? Like:

    vehicles.OrderBy(v => v.maxSpeed).ToList();
    
    0 讨论(0)
  • 2020-12-12 19:55

    Great solution over here...

    Passing properties by reference in C#

    void GetString<T>(string input, T target, Expression<Func<T, string>> outExpr)
    {
        if (!string.IsNullOrEmpty(input))
        {
            var expr = (MemberExpression) outExpr.Body;
            var prop = (PropertyInfo) expr.Member;
            prop.SetValue(target, input, null);
        }
    }
    
    void Main()
    {
        var person = new Person();
        GetString("test", person, x => x.Name);
        Debug.Assert(person.Name == "test");
    }
    
    0 讨论(0)
提交回复
热议问题