Cast Object to Generic List

后端 未结 8 1287
野趣味
野趣味 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:11

    I ran into same problem - I have a collection which data type is only known at run time and I can't cast it to anything. None of the solutions above worked. Finally I solved it by serializing to JSON and de-serializing back. Of course it's not ideal, but may help someone.

    string jsonString = JsonConvert.SerializeObject(myObject);
    jsonString = "{ values:" + jsonString + "}";
    
    JObject j = JObject.Parse(jsonString);
    
    //now we can iterate over the list
    foreach (var x in j["values"])
    {
        string name = x.ToString();
        ...
    }
    

提交回复
热议问题