通过反射在数组中设置值 [英] Setting value in an array via reflection

查看:40
本文介绍了通过反射在数组中设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 C# 中通过反射在数组属性中设置单个值?

Is there a way to set a single value in an array property via reflection in c#?

我的属性定义如下:

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!

顺便说一句:我尝试使用 index 参数,但这似乎只适用于索引属性,而不适用于数组属性...

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

推荐答案

当你这样做时:

obj.Thresholds[i] = value;

在语义上等同于:

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

这意味着您根本不需要 SetValue ;相反,您想使用 GetValue 获取数组,然后对数组进行变异.如果已知类型为 double[],则:

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;

否则可能是非通用的 IList 方法(因为数组实现了 IList):

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

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

如果是多维数组,则必须使用Array代替IList.

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

这篇关于通过反射在数组中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆