I want to to cast a list of object type A to a list of object type B, where A inherit B.
Concretely :
public class A : B
{
public string name { get; set; }
}
public class B
{
public B() { }
}
I parse a JSON string that I cast to my list of type A :
B elem = ((JArray)_configuration).ToObject<List<A>>();
And I have this error :
Cannot implicitly convert type 'System.Collections.Generic.List< A>' to 'System.Collections.Generic.List< B>'
I tried to cast it :
List<B> elem = (List<B>)((JArray)_configuration).ToObject<List<A>>();
but got this error :
Cannot convert type 'System.Collections.Generic.List< A>' to 'System.Collections.Generic.List< B>'
I couldn't find help, maybe because I don't know what to look for, so apologies if it has been answered somewhere already !
答案 0 :(得分:2)
您可以使用catch(CUserException *e)
。
Enumerable.Cast<>()
但是List<B> list = myList.Cast<B>().ToList();
会创建一个副本。如果你只想迭代这些项目。请勿使用ToList()
并将其作为ToList()
处理。它会在飞行中变得懒惰。
答案 1 :(得分:0)
好的,只要找到答案就可以提供帮助。如果没有,请告诉我,我将删除该问题。对不起!
只需要这样做:
List<B> elem = new List<B>(((JArray)_configuration).ToObject<List<A>>());
答案 2 :(得分:0)
也许你应该阅读this,使用list.selectall。
您也可以尝试this for arrays。