c# - 通过反射设置索引值给了我 TargetParameterCountException

标签 c# .net reflection

我有一个 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/

相关文章:

java - 为什么反射 api 在测试用例中不起作用

c# - 发出局部变量并为其赋值

c# - 带有功能区的 Visual Studio 图像 (XML)

c# - 已编译的Azure函数监控: "No data available"

.net - 使用事件目录中的信息解锁窗口

c# - 防止外部代码修改C#中的私有(private)数据

c# - 在 MVC 中清除 View 引擎会破坏站点地图面包屑样式

c# - 这个 C# 对象初始化程序代码发生了什么?

c# - ASP.MVC HandleError 属性不起作用

.net - 如何创建从 MSMQ 消息队列中读取的 IObservable<T>?