Refer to a property name by variable

前端 未结 4 660
不知归路
不知归路 2021-01-01 02:12

Is there a way to refer to a property name with a variable?

Scenario: Object A have public integer property X an Z, so...

public void setProperty(in         


        
4条回答
  •  既然无缘
    2021-01-01 02:30

    Not in the way your suggesting, but yes it is doable. You could use a dynamic object (or even just an object with a property indexer) e.g.

    string property = index == 1 ? "X" : "Z";
    A[property] = value;
    

    Or alternatively by using Reflection:

    string property = index == 1 ? "X" : "Z";
    return A.GetType().GetProperty(property).SetValue(A, value);
    

提交回复
热议问题