c# - 反射——从类型到类(不是类的实例)

标签 c# reflection json-deserialization

我怎么写这样的东西?

string json = null;
Type[] types = Assembly.GetExecutingAssembly().GetTypes();
var carTypes = (from type in types
                 where type.IsClass && type == typeof(Car)
                 select type);
foreach(var carType in carTypes )
{
    string typeName = carType .Name;
    string jsonFile = typeName + ".json";
    json = File.ReadAllText(jsonFile);

    // How can I not hardcode "Porche" here and instead use "carType"?
    IList<Porche> cars = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Porche>>(json);
}

在这里,PorcheCar 的子类 - “Porche”和“Car”都是。除了保时捷,我们还有丰田、宝马、特斯拉……我想通过反射动态检索它们(避免硬编码) "cars" 是汽车的实例列表。

carType”是类型。 如何在以 List 作为参数的 JsonConvert.DerserializeObject 中使用“carType”?

IList<someReflectionAPI(carType)> cars = Newtonsoft.Json.JsonConvert.DeserializeObject<List<someReflectionAPI(carType)>>(json);

谢谢

最佳答案

您可以在运行时使用 MakeGenericType 创建通用类型并使用 DeserializeObject 的非泛型重载:

var listOfType = typeof(List<>).MakeGenericType(carType);
var cars = JsonConvert.DeserializeObject(json, listOfType);

关于c# - 反射——从类型到类(不是类的实例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623671/

相关文章:

c# - 分组/排序/分割二维列表/数组

c# - 反序列化 JSON (Json.NET)

c# - 如何在 Xamarin Android 的选项卡之间传递数据?

c# - 为什么 Linq 无法将表达式翻译/视为本地表达式并引发异常?

java - 如何通过字符串类名在GWT中创建新对象?

c# - 自定义,复杂的动态反射解决方案-C#

c# - 将 Json 对象反序列化为 C# 对象不起作用

android - 在 Kotlin 中使用 Gson 解析 JSON 数组

c# - 在C#中获取用户IP

JAVA REFLECTION : java. lang.IllegalArgumentException:参数类型不匹配