小编Lef*_*lou的帖子

使用Reflection的C#中索引属性的SetValue

我有一个班级有一个

ObservableCollection<int>
Run Code Online (Sandbox Code Playgroud)

作为属性,我正在尝试更改该类实例的属性内的值.这是我的代码,并且得到了一个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, …
Run Code Online (Sandbox Code Playgroud)

c# reflection

10
推荐指数
1
解决办法
4792
查看次数

标签 统计

c# ×1

reflection ×1