Refer to a property name by variable

僤鯓⒐⒋嵵緔 提交于 2020-06-08 02:37:07

问题


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(int index, int value)
{
    string property = "";

    if (index == 1)
    {
        // set the property X with 'value'
        property = "X";
    }
    else 
    {
        // set the property Z with 'value'
        property = "Z";
    }

    A.{property} = value;
}

This is a silly example so please believe, I have an use for this.


回答1:


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.




回答2:


I think you mean reflection:

PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
info.SetValue(myObject, myValue);



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/13292078/refer-to-a-property-name-by-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!