列表<object>使用反射列出<T>

Bur*_*and 6 c# json

我正在滚动一个json转换器,我的属性装饰有映射名称.我正在使用反射来使用该映射描述来确定要创建的对象类型以及它的映射方式.以下是一个例子......

[JsonMapping("location", JsonMapping.MappingType.Class)]
    public Model.Location Location { get; set; }
Run Code Online (Sandbox Code Playgroud)

我的绘图工作正常,直到我到达集合...

[JsonMapping("images", JsonMapping.MappingType.Collection)]
    public IList<Image> Images { get; set; }
Run Code Online (Sandbox Code Playgroud)

问题是我无法将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;
    }
Run Code Online (Sandbox Code Playgroud)

这使我返回List,但是反射要求我在执行property.SetValue之前实现IConvertable.

有人知道更好的方法吗?

Boj*_*nik 2

您可以使用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;    
}
Run Code Online (Sandbox Code Playgroud)