通过反射设置索引值会给我TargetParameterCountException

时间:2015-12-28 11:55:27

标签: c# .net reflection

我有一个包含顶点属性的PolygonRenderer类,它是一个List,用于保存类渲染的多边形的点。

当我尝试通过反射更改此列表中的特定点时,我在函数的最后一行得到 System.Reflection.TargetParameterCountException

    public override void ApplyValue(string property, object value, int? index)
    {
        List<PropertyInfo> properties = Data.GetType().GetProperties().ToList();
        PropertyInfo pi = properties.FirstOrDefault(p => p.Name == property);
        pi.SetValue(Data, value,
            index.HasValue ? new object[] { index.Value } : null);
    }

当我调试时,我得到index.Value = 3,Data是PolygonRenderer实例,pi反映了Vertices属性,count = 4。

由于我的索引应该是我列表中的最后一项,我怎么可能在该属性上得到一个计数异常?

由于

1 个答案:

答案 0 :(得分:2)

  

我有一个包含Vertices属性的PolygonRenderer类,它是一个List ...

所以你需要执行类似这样的事情

Data.Vertices[index] = value

以及您的代码尝试做的是

Data[index] = value

你可以使用类似的东西

public override void ApplyValue(string property, object value, int? index)
{
    object target = Data;
    var pi = target.GetType().GetProperty(property);
    if (index.HasValue && pi.GetIndexParameters().Length != 1)
    {
        target = pi.GetValue(target, null);
        pi = target.GetType().GetProperties()
            .First(p => p.GetIndexParameters().Length == 1
            && p.GetIndexParameters()[0].ParameterType == typeof(int));
    }
    pi.SetValue(target, value, index.HasValue ? new object[] { index.Value } : null);
}