【发布时间】: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