拥有动态类型:
Type targetType;
if (position.Length == 1)
{
targetType = typeof (Row);
}
if (position.Length == 4)
{
targetType = typeof (Field);
}
在此之后,我需要将JSON反序列化为此类型的List:
List<targetType>
代码:
var components = JsonConvert.DeserializeObject<List<targetType>>(include.components.ToString());
我是如何做到的?
答案 0 :(得分:0)
您可以将JsonConvert.DeserializeObject(String, Type)
与Type.MakeGenericType(Type[])
一起使用:
var components = (IList)JsonConvert.DeserializeObject(include.components.ToString(), typeof(List<>).MakeGenericType(new[] { targetType }));
顺便提一下,如果include.components
是JToken
,那么使用JToken.ToObject(Type)
会更有效:
var components = (IList)include.components.ToObject(typeof(List<>).MakeGenericType(new[] { targetType }));