我知道这不起作用,但有没有人有办法使它工作?
object obj = new object(); MyType typObj = new MyType(); obj = typObj; Type objType = typObj.GetType(); Listlist = new List (); list.add((objType) obj);
编辑:
这是当前的代码:http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs
我试图简化的方法是SingleNodeCollection
正如您所看到的,它目前使用了如此混乱的反射方法.
看来你错过了一个明显的解决方案:
object obj = new object(); MyType typObj = new MyType(); obj = typObj; Listlist = new List (); list.Add((MyType) obj);
如果你真的需要动态路线,那么你可以这样做:
object obj = new object(); MyType typObj = new MyType(); obj = typObj; Type objType = typObj.GetType(); Type listType = typeof(List<>); Type creatableList = listType.MakeGenericType(objType); object list = Activator.CreateInstance(creatableList); MethodInfo mi = creatableList.GetMethod("Add"); mi.Invoke(list, new object[] {obj});