Refer to a property name by variable

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

    Easy:

    a.GetType().GetProperty("X").SetValue(a, value);
    

    Note that GetProperty("X") returns null if type of a has no property named "X".

    To set property in the syntax you have provided just write an extension method:

    public static class Extensions
    {
        public static void SetProperty(this object obj, string propertyName, object value)
        {
            var propertyInfo = obj.GetType().GetProperty(propertyName);
            if (propertyInfo == null) return;
            propertyInfo.SetValue(obj, value);
        }
    }
    

    And use it like this:

    a.SetProperty(propertyName, value);
    

    UPD

    Note that this reflection-based method is relatively slow. For better performance use dynamic code generation or expression trees. There are good libraries that can do this complex stuff for you. For example, FastMember.

    0 讨论(0)
  • 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<int> setValue;
    
        if (index == 1)
        {
            // set property X
            setValue = x => A.X = x;
        }
        else
        {
            // set property Z
            setValue = z => A.Z = z;
        }
    
        setValue(value);
    }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-01 02:54

    I think you mean reflection:

    PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
    info.SetValue(myObject, myValue);
    
    0 讨论(0)
提交回复
热议问题