C#中的动态类型

时间:2009-06-04 16:06:07

标签: c# dynamic-typing

我知道这不起作用,但有没有人有办法让它发挥作用?

object obj = new object();
MyType typObj = new MyType();
obj = typObj;
Type objType = typObj.GetType();
List<objType> list = new List<objType>();
list.add((objType) obj);

编辑:

以下是当前代码:http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs

我尝试简化的方法是SingleNodeCollection

正如您所看到的,它目前使用了如此混乱的反射方法。

8 个答案:

答案 0 :(得分:10)

似乎你错过了一个明显的解决方案:

object obj = new object();
MyType typObj = new MyType();
obj = typObj;
List<MyType> list = new List<MyType>();
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});

答案 1 :(得分:1)

你需要反思:

constructor = typeof (MyType).GetConstructor () // doing this from memory, the typeof might be wrong, I'm sure someone will edit it
typObj = (MyType) constructor.Invoke ()

它也可以用于泛型,但这有点棘手。

答案 2 :(得分:1)

你可以使用Generics做这样的事情,但我不确定它的重点是什么。

public List<T> TypedList<T>() where T : new()
{
    object obj = new object();
    T typObj = new T();
    obj = typObj;
    List<T> list = new List<T>();
    list.Add((T)obj);
    return list;
}

答案 3 :(得分:0)

object obj = new object();
Type objType = obj.GetType();
IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(objType));
list.Add(obj);

如果您尝试将某些内容放入无法从objType分配的列表中,您将收到运行时错误。

答案 4 :(得分:0)

更快的是使用Reflection.Emit Here's一个使用Reflection.Emit在运行时实例化任意具体类型的简单示例。为了您的目的,您只需要在示例中调用List的ctor而不是T.ctor。

答案 5 :(得分:0)

即使它似乎得到回答,我仍然没有得到它:)

将“typeToReturn”作为函数的通用参数不是很有用吗?

public List<T> SingleNodeCollection<T>(String xPath, XPathNavigator navigator)
  where T : new()
{
  XPathNodeIterator nodes = navigator.Select(xPath);
  List<T> returnedList = new List<T>(nodes.Count);
  ...
  T newObj = new T();
  ...
  Type t = typeof(T); // need the type anyway?
}

答案 6 :(得分:0)

  public class myClass
  {
  }

  myClass instance = new myClass();

  Type t = instance.GetType;

// top只是为了显示获取类型...

public object GetListOfType(Type t)
{
  Type listType = typeof(List<>);
  var listOfType = listType.MakeGenericType(t);

  var listOfMyClassInstance = Activator.CreateInstance(listOfType); 

  return listOfMyClassInstance;
}

但最终你必须直接使用你的类型

  List<object> listOfMyClass = GetListOfType(t);
  listOfMyClass.Add(myClassInstance);

  ((myClass)listOfMyClass[0]).SomeProperty

答案 7 :(得分:-2)

我不完全确定你要做什么,但这会有效:

var obj = new MyType();

我可能会误解你的问题。

(我编辑了这个来修复无法编译的示例代码,感谢评论)

相关问题