How do I get the name of a property from a property in C# (2.0)

后端 未结 7 690
春和景丽
春和景丽 2020-12-10 17:24

I know I could have an attribute but that\'s more work than I want to go to... and not general enough.

I want to do something like

class Whotsit
{
          


        
7条回答
  •  一个人的身影
    2020-12-10 17:56

    No, there's nothing to do this. The expression whotsit.TestProp will evaluate the property. What you want is the mythical "infoof" operator:

    // I wish...
    MemberInfo member = infoof(whotsit.TestProp);
    

    As it is, you can only use reflection to get the property by name - not from code. (Or get all the properties, of course. It still doesn't help you with your sample though.)

    One alternative is to use an expression tree:

    Expression> = () => whotsit.TestProp;
    

    then examine the expression tree to get the property.

    If none of this helps, perhaps you could tell us more about why you want this functionality?

提交回复
热议问题