【发布时间】:2011-08-18 04:10:57
【问题描述】:
我有一个特定类型的对象的 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
没有可用于数组的 ToList(),这是我正在寻找的行为
object returnValue = typedArray.ToList();
所以基本上我将类型名称作为字符串,我可以从名称创建一个类型,并创建一个包含多个类型化对象的集合,但是如何将其转换为列表?我正在为属性补水,当我执行 SetValue 时,我的属性类型需要匹配。
非常感谢。
【问题讨论】:
-
你知道编译时的类型,还是动态的?
-
动态,我从 JSON 转换,我知道类型为字符串,我可以创建类型化对象数组,但我需要输出为 List
-
所以...您正试图将 Array(类型化)转换为 List
,对吗?并且您将“type T”的名称存储在一个字符串(和一个 Type 对象)中。