Han*_*ans 2 c# generics reflection collections casting
我有一个带有通用List属性的对象,其中T是原始值,字符串或枚举。此列表的泛型参数永远不会是引用类型(字符串除外)。现在,我有另一个参数类型为object的List。有没有一种方法可以在我的对象列表中设置该属性的值?如:
List<object> myObjectList = new List<object>();
myObjectList.Add(5);
property.SetValue(myObject, myObjectList, null);
Run Code Online (Sandbox Code Playgroud)
当我知道该属性的真实类型是:
List<int>
Run Code Online (Sandbox Code Playgroud)
我能看到的唯一解决方案是进行硬编码开关,该开关使用list属性的通用参数的类型并创建类型安全的列表。但是,最好有一个通用的解决方案。谢谢!
您应该创建属性的实际类型的实例,如果你知道它真的会成为List<T>一些T(而不是一个接口,例如)。然后,您可以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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5943 次 |
| 最近记录: |