Pass property itself to function as parameter in C#

后端 未结 7 1613
春和景丽
春和景丽 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:50

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

    Function's parameter is this: System.Func

    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 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);
    

提交回复
热议问题