Refer to a property name by variable

前端 未结 4 671
不知归路
不知归路 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:29

    It's hard for me to understand what you're trying to achieve... if you're trying to determine the property and value separately, and at different times, you can wrap the act of setting the property inside a delegate.

    public void setProperty(int index, int value)
    {
        Action setValue;
    
        if (index == 1)
        {
            // set property X
            setValue = x => A.X = x;
        }
        else
        {
            // set property Z
            setValue = z => A.Z = z;
        }
    
        setValue(value);
    }
    

提交回复
热议问题