我有一个 PolygonRenderer 类,其中包含一个 顶点 属性,它是一个列表,保存类渲染的多边形的点。
当我尝试通过反射更改此列表中的特定点时,我在函数的最后一行收到 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 反射(reflect)了 Vertices 属性,计数 = 4。
由于我的索引应该是列表的最后一项,我怎么可能在该属性上出现计数异常?
谢谢
最佳答案
I have a PolygonRenderer class containing a Vertices property, which is a 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);
}
关于c# - 通过反射设置索引值给了我 TargetParameterCountException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34493082/