将对象转换回这样的通用列表的正确代码是什么?
Type x = typeof(MyClass);
object o = new List<MyClass>();
List<x> l = o as List<x>; // Not working
编辑:也许还不是很清楚:该对象是一个泛型类型的列表,我在编译时不知道.. 不过 List 有像“Add”这样的函数,我无论如何都可以调用,比如:
l.Add((new MyClass() as object)) as x);
List<MyClass> l = (List<MyClass>)o;
或者
List<MyClass> l = o as List<MyClass>;
你的意思是
List<> l = o as List<>;
除非您使用泛型类,否则这是不可能的:
class C<T>
{
public List<T> List = new List<T>();
}
用法:
C<MyClass> c = new C<MyClass>();
c.List.Add(new MyClass());
最后我得到了OP的目标:
Type listType = typeof(List<>);
Type targetType = listType.MakeGenericType(typeof(YourClass));
List<YourClass> list = (List<YourClass>)Activator.CreateInstance(targetType);
有关详细信息,请参阅MSDN。
当泛型接口因为编译时不知道类型参数而无法使用,但非泛型接口可用时,您可以改用它:
Type x = typeof(MyClass);
object o = new List<MyClass>();
IList l = (IList)o;
l.Add(new MyClass());
非泛型IList
接口由泛型List<T>
类实现。
object testobject = new List<string>();
List<string> list = (List<string>)testobject;
List<Employee> employees = new List<Employee> { new Employee { Id = Guid.NewGuid().ToString(), Name = "SOME" }, new Employee { Id = Guid.NewGuid().ToString(), Name = "SOME2" } };
object obj = employees;
List<Employee> unBoxed = (List<Employee>)obj;