投对象泛型列表 [英] Cast Object to Generic List
问题描述
我有3个generict类型列表
I have 3 generict type list.
List<Contact> = new List<Contact>();
List<Address> = new List<Address>();
List<Document> = new List<Document>();
和保存与对象类型的变量。现在我做NEDD铸返回列表它进行一个foreach,有的像这样的:
And save it on a variable with type object. Now i nedd do Cast Back to List to perfom a foreach, some like this:
List<Contact> = (List<Contact>)obj;
但OBJ含量的变化每一次,我有一些这样的:
But obj content change every time, and i have some like this:
List<???> = (List<???>)obj;
我有另一个变量保持电流obj类型:
I have another variable holding current obj Type:
Type t = typeof(obj);
我可以做这样的事情的一些??:
Can i do some thing like that??:
List<t> = (List<t>)obj;
观测:我没有当前类型列表中,但我需要投,我现在另一个不的形式:
Obs: I no the current type in the list but i need to cast , and i dont now another form instead:
List<Contact> = new List<Contact>();
帮助PLZ !!!
Help Plz!!!
推荐答案
什么是棘手的问题。试试这个:
What a sticky problem. Try this:
List<Contact> c = null;
List<Address> a = null;
List<Document> d = null;
object o = GetObject();
c = o as List<Contact>;
a = o as List<Address>;
d = o as List<Document>;
℃之间,一个和d,有2零点和1个非空,或3空值。
Between c, a, and d, there's 2 nulls and 1 non-null, or 3 nulls.
以2:
object o = GetObject();
IEnumerable e = o as IEnumerable;
IEnumerable<Contact> c = e.OfType<Contact>();
IEnumerable<Address> a = e.OfType<Address>();
IEnumerable<Document> d = e.OfType<Document>();
这篇关于投对象泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!