Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...