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 set a single value in an array property via reflection in c#?

My property is defined like this:

double[]    Thresholds      { get; set; }

For "normal" properties I use this code to set it via reflection:

PropertyInfo pi = myObject.GetType().GetProperty(nameOfPropertyToSet);
pi.SetValue(myObject, Convert.ChangeType(valueToSet, pi.PropertyType), null);

How would I have to change this code to set the value in an array property at an arbitrary position? Thanks!

BTW: I tried to use the index parameter, but that seems only to work for indexed properties, not properties that are arrays...

See Question&Answers more detail:os

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

1 Answer

When you do:

obj.Thresholds[i] = value;

that is semantically equivalent to:

double[] tmp = obj.Thresholds;
tmp[i] = value;

which means you don't want a SetValue at all; rather, you want to use GetValue to obtain the array, and then mutate the array. If the type is known to be double[], then:

double[] arr = (double[]) pi.GetValue(myObject, null);
arr[i] = value;

otherwise perhaps the non-generic IList approach (since arrays implement IList):

IList arr = (IList) pi.GetValue(myObject, null);
arr[i] = value;

If it is a multi-dimensional array, you'll have to use Array in place of IList.


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