在通过反射阵列设定值 [英] Setting value in an array via reflection

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

问题描述

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

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

有关正常的性质我用这个code通过反射来进行设置:

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

我如何将不得不改变这个code设置在任意位置数组中的属性的值?
谢谢!

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

BTW:我试图使用索引参数,但似乎只为索引的属性,没有属性是数组工作...

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 来获得数组,然后变异的数组。如果类型是已知的双[] ,则:

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

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

如果它是一个多维数组,你将不得不使用阵列的IList 的。

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

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

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