[英]List<object> To List<T> using reflection
我正在滚动一个json转换器,我的属性装饰有映射名称。 我正在使用反射来使用该映射描述来确定要创建的对象类型以及它的映射方式。 以下是一个例子......
[JsonMapping("location", JsonMapping.MappingType.Class)]
public Model.Location Location { get; set; }
我的绘图工作正常,直到我到达集合...
[JsonMapping("images", JsonMapping.MappingType.Collection)]
public IList<Image> Images { get; set; }
问题是我无法将List转换为属性的列表类型。
private static List<object> Map(Type t, JArray json) {
List<object> result = new List<object>();
var type = t.GetGenericArguments()[0];
foreach (var j in json) {
result.Add(Map(type, (JObject)j));
}
return result;
}
这使我返回List,但是反射要求我在执行property.SetValue之前实现IConvertable。
有人知道更好的方法吗?
您可以使用Type.MakeGenericType创建正确类型的List
对象:
private static IList Map(Type t, JArray json)
{
var elementType = t.GetGenericArguments()[0];
// This will produce List<Image> or whatever the original element type is
var listType = typeof(List<>).MakeGenericType(elementType);
var result = (IList)Activator.CreateInstance(listType);
foreach (var j in json)
result.Add(Map(type, (JObject)j));
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.