我有一个具有通用 List 属性的对象,其中 T 是原始值、字符串或枚举。此列表的通用参数永远不会是引用类型(字符串除外)。现在,我有另一个参数类型为对象的列表。有没有办法用我的对象列表设置该属性的值?如:
List<object> myObjectList = new List<object>();
myObjectList.Add(5);
property.SetValue(myObject, myObjectList, null);
当我知道属性的真实类型是:
List<int>
我能看到的唯一解决方案是制作一个硬编码开关,该开关使用列表属性的通用参数类型并创建一个类型安全列表。但如果有一个通用的案例解决方案,那将是最好的。谢谢!
最佳答案
如果您知道它确实是一个List<T>
,您应该创建一个属性真实类型的实例。对于一些 T
(而不是接口(interface),例如)。然后您可以转换为 IList
并在不知道实际类型的情况下向其添加值。
object instance = Activator.CreateInstance(property.PropertyType);
// List<T> implements the non-generic IList interface
IList list = (IList) instance;
list.Add(...); // Whatever you need to add
property.SetValue(myObject, list, null);
关于C# 如何在其类型为 List<T> 且我有一个 List<object> 时设置 PropertyInfo 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25757121/