Cast Object to Generic List

后端 未结 8 1202
野趣味
野趣味 2020-12-03 03:37

I have 3 generict type list.

List = new List();
List
= new List
(); List = new Lis
相关标签:
8条回答
  • 2020-12-03 04:17

    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>();
    
    0 讨论(0)
  • 2020-12-03 04:24

    No, you can't cast without going around corners (this is: reflection), generic type parameters have to be known at compile time. You can of course do something like this:

    content.Where(o => o is type).ToList().Foreach(stuff);

    0 讨论(0)
提交回复
热议问题