我怎么写这样的东西?
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);
}
在这里,Porche 是 Car 的子类 - “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/