我有一个特定类型的对象的ArrayList,我需要将此ArrayList转换为类型列表.这是我的代码
Type objType = Type.GetType(myTypeName);
ArrayList myArrayList = new ArrayList();
object myObj0 = Activator.CreateInstance(type);
object myObj1 = Activator.CreateInstance(type);
object myObj2 = Activator.CreateInstance(type);
myArrayList.Add(myObj0);
myArrayList.Add(myObj1);
myArrayList.Add(myObj2);
Array typedArray = myArrayList.ToArray(objType); // this is typed
object returnValue = typedArray.ToList(); // this is fake, but this is what I am looking for
Run Code Online (Sandbox Code Playgroud)
没有可用于数组的ToList(),这是我正在寻找的行为
object returnValue = typedArray.ToList();
Run Code Online (Sandbox Code Playgroud)
所以我基本上把类型名称作为字符串,我可以从名称创建一个Type,并创建一个包含几个对象类型的集合,但是如何将其转换为List?我正在保护一个属性,当我做一个SetValue时,我的属性类型需要匹配.
非常感谢你.
如果您使用的是.NET 4,动态类型可以提供帮助 - 它可以执行类型推断,因此您可以调用ToList,但不能作为扩展方法:
dynamic typedArray = myArrayList.ToArray(objType);
object returnValue = Enumerable.ToList(typedArray);
Run Code Online (Sandbox Code Playgroud)
否则,你需要使用反射:
object typedArray = myArrayList.ToArray(objType);
// It really helps that we don't need to work through overloads...
MethodInfo openMethod = typeof(Enumerable).GetMethod("ToList");
MethodInfo genericMethod = openMethod.MakeGenericMethod(objType);
object result = genericMethod.Invoke(null, new object[] { typedArray });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6867 次 |
| 最近记录: |