我有一个类

ObservableCollection<int>

作为属性,而我正在尝试更改该类实例的属性内的值。这是我拥有的代码,并且正在获取TargetException:
object[] index = null;
var originalPropertyName = propertyName;
if (propertyName.Contains("[") && propertyName.Contains("]"))
{
    index = new object[1];
    index[0] = Convert.ToInt32(propertyName.Split('[')[1].Split(']')[0]);
    propertyName = propertyName.Split('[')[0];
}
PropertyInfo pi = item.GetType().GetProperty(propertyName);
PropertyInfo opi = item.GetType().GetProperty(originalPropertyName);
Type pType = index != null ? pi.PropertyType.GetGenericArguments()[0] : pi.PropertyType;
if (pi != null)
{
    object convertedValue = Convert.ChangeType(value, pType);
    if (index == null)
    {
        item.GetType().GetProperty(propertyName).SetValue(item, convertedValue, null);
    }
    else
    {
        //PropertyInfo ipi = pi.PropertyType.GetProperties().Single(p => p.GetIndexParameters().Length > 0);
        //var collection = pi.GetValue(item, index);
        //collection.GetType().GetProperty("Value").SetValue(collection, convertedValue, null);
        var _pi = pi.PropertyType.GetProperty("Item");
        _pi.SetValue(pi, convertedValue, index);
    }
}

上面没有显示如何获取propertyName,但是在使用索引属性的情况下,它的生命始于“IndexedProperty [10]”。

在“其他”之后的评论中,通过阅读其他一些stackoverflow帖子以及其他论坛上的操作方法,您可以查看我尝试过的其他操作,但是到目前为止,我还是失败了。有任何想法吗?

将属性强制转换为ObservableCollection是不可行的,因为我希望它是动态的。

整个概念的要点是拥有一个数据绑定(bind)的DataGrid,并通过更新每个实例的适当属性来正确地执行粘贴操作,而不管这些属性是否已建立索引。非索引属性可以正常工作,但是我无法使ObservableCollection的属性正常工作。

最佳答案

从传统意义上讲,将ObservableCollection<int>作为属性的类实际上没有索引属性。它只是具有一个非索引属性,该属性本身具有一个索引器。因此,您需要使用GetValue开头(不指定索引),然后在结果上获取索引器。

基本上,您需要记住:

foo.People[10] = new Person();

等效于:
var people = foo.People; // Getter
people[10] = new Person(); // Indexed setter

似乎您已经快要被注释掉的代码了:
//var collection = pi.GetValue(item, index);
//collection.GetType().GetProperty("Value").SetValue(collection, convertedValue, null);

...但是您在错误的位置应用了索引。您想要(我认为-问题并不十分清楚):
var collection = pi.GetValue(item, null);
collection.GetType()
          .GetProperty("Item") // Item is the normal name for an indexer
          .SetValue(collection, convertedValue, index);

关于c# - 使用反射的C#中的索引属性的SetValue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14052812/

10-12 04:03
查看更多