【问题标题】:Given a PropertyInfo object from System relfection that I know to be a list, how can I access the list and manipulate the items within the list?给定来自 System relfection 的 PropertyInfo 对象,我知道它是一个列表,我如何访问该列表并操作列表中的项目?
【发布时间】:2020-10-20 22:22:37
【问题描述】:

所以我对 Reflection 还很陌生,但最近发现它非常有用。但我遇到了障碍。基本上现在我正在循环使用反射获得的类的属性,并根据属性包含的数据类型(int、string、enum 等)做一些事情,并在这样做时修改属性中的数据.使用 propertyInfo.SetValue() 方法非常简单,该方法适用于我需要处理的所有其他情况。但是,对于一个列表,我不能只设置值,因为我不想设置列表的值,我希望能够从列表中添加和删除项目以及更改列表中项目的值。而这一切都是动态的。下面是我正在尝试做的一个例子:

MyAbstractClass classInstance; //this may contain one of many classes inheriting from 'MyAbstractClass'

PropertyInfo[] properties = classInstance.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
     //this would be proceeded by other type case checks, this is the case that it's a list
     else if (prop.PropertyType.GetInterface(typeof(List<>).FullName) != null)
     {
          Type contentType = prop.PropertyType.GetGenericArguments()[0]; //get the type of data held in list
          //BEGIN EXAMPLES OF WHAT I'D LIKE TO DO
          prop.GetValue(classInstance).Add(Activator.CreateInstance(contentType));
          prop.GetValue(classInstance).RemoveAt(3);
          prop.GetValue(classInstance)[1] = someDataThatIKnowIsCorrectType;
     }
}

仅通过互联网研究,我就发现了很多其他东西并学到了很多东西,但我一直无法找到我正在尝试拼凑的最后一块拼图,或者可能无法找到解决我问题的方法如果我确实看到的话。

感谢您的帮助!

【问题讨论】:

    标签: c# list system system.reflection propertyinfo


    【解决方案1】:

    您可以将值转换为IList 并使用Add(object value) 方法:

    class MyClass
    {
        public List<int> MyProperty { get; set; }
    }
    
    var x = new MyClass {MyProperty = new List<int>()};
    var list = (IList)x.GetType().GetProperty(nameof(MyClass.MyProperty)).GetValue(x);
    list.Add(1);
    list.Add(2);
    list.RemoveAt(0);
    list[0] = 3;
    Console.WriteLine(list[0]); // prints 3
    

    我个人也会像这样实现属性类型检查:

    var isIList = prop.PropertyType.GetInterfaces().Any(i => i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(IList<>))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 2018-05-15
      • 2022-12-18
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多