Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c# - Cast Object to Generic List

I have 3 generict type list.

List<Contact> = new List<Contact>();
List<Address> = new List<Address>();
List<Document> = new List<Document>();

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;

But obj content change every time, and i have some like this:

List<???> = (List<???>)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>();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>;

Between c, a, and d, there's 2 nulls and 1 non-null, or 3 nulls.


Take 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>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...