Setting value in an array via reflection

人盡茶涼 提交于 2019-11-29 13:40:11

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.

Bas

You are not actually setting the property, just changing the property value:

object value = myObject.GetType().GetProperty(nameOfPropertyToset).GetValue(myObject, null);

if (value is Array)
{
    Array arr = (Array)value;
    arr.SetValue(myValue, myIndex);
}
else
{
    ...
}

Te code here will work for on it, its design to fill a 10 position array, you can do it for any size array.

The function PopulateInstance populate a data structure with what I need.

    object singleval;
    Array arrayval;
    System.Type LocalPType = obj.GetType().GetField(node.Name).FieldType;
    if (LocalPType.IsArray)
    {
        singleval = TreeNodeProperty.CreateNewInstance(LocalPType.GetElementType());
        arrayval =  Array.CreateInstance(LocalPType, 10);
        for(int i = 0; i < 10; i++)
        {
            singleval = PopulateInstance(singleval, node);
            arrayval.SetValue(singleval, i);
        }
        obj.GetType().GetField(node.Name).SetValue(obj, arrayval);
    }
    else
    {
        object val;
        val = Activator.CreateInstance(LocalPType);
        obj.GetType().GetField(node.Name).SetValue(obj,         PopulateInstance(val, node));
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!