积极答复者
(C#)泛型变量是否可以实现?

问题
答案
-
是的,目前不支持。
Microsoft Online Community Support- 已标记为答案 Steven Shan 2010年2月11日 4:02
全部回复
-
你好,
你上面的已经是泛型了吧。
详细情况参考下面文档。
http://msdn.microsoft.com/zh-cn/library/sz6zd40f.aspx
http://www.cnblogs.com/jams742003/articles/1273358.html
Microsoft Online Community Support -
// type parameter T in angle brackets public class GenericList<T> { // The nested class is also generic on T. private class Node { // T used in non-generic constructor. public Node(T t) { next = null; data = t; } private Node next; public Node Next { get { return next; } set { next = value; } } // T as private member data type. private T data; // T as return type of property. public T Data { get { return data; } set { data = value; } } } private Node head; // constructor public GenericList() { head = null; } // T as method parameter type: public void AddHead(T t) { Node n = new Node(t); n.Next = head; head = n; } public IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } } }
Microsoft Online Community Support -
public class SomeClass { SomeType objectA; public void SomeMethod() { SomeGenericMethods<objectA.GetType()>(); } public void SomeGenericMethods<T>() { } }
请注意一下objectA.GetType()的部分,意思就是在泛型参数这里如何通过将泛型参数记录在变量内,在适当的时候可以将变量内的信息(泛型参数)传递给一个泛型方法中的泛型参数。也就是说动态的产生泛型参数,而不是事先了解泛型参数是什么类型的,您上面所说的是个泛型类,一般的用法都是静态的完成泛型类的创建如:List<int> listA,这样是个静态的,实现已经知道泛型参数是int。那么需要解决的问题是如果有多个实例(已知)但是不知道实例的类型(当然类型可以通过反射来获取),那么如何动态的创建这样的List<T>来完成将这些实例的类型作为泛型参数呢? -
不太理解。
你想要什么类型就传什么类型进去,为什么还要动态呢。
比如List<T>,你想要string类型就是List<string>。这个是在你使用的时候指定的。
另外采用你这样的反射也是不行的。
List<objectA.GetType()> list=new List<objectA.GetType()>()
如果你在使用泛型的时候还不确定是什么类型那编译器如何编译。比如你上面这种方式,编译器会报缺少一个类型参数之类的错。
编译时和运行时是有区别的。也许从运行时的角度看上面这种方式是可以理解的,但是编译的时候计算机是不知道objectA.GetType()是什么的。
Microsoft Online Community Support -
是的,目前不支持。
Microsoft Online Community Support- 已标记为答案 Steven Shan 2010年2月11日 4:02