反射 - 从 Type 到 Class(不是 class 的实例)
Reflection - from Type to Class (not instance of class)
我怎么写这样的东西?
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 的子 class - Both "Porche”和“Car”是Class。除了保时捷,我们还有丰田、宝马、特斯拉……我想通过反射动态检索它们(避免硬编码)
"cars" 是 个实例 汽车的列表。
"carType" 是 Type。
如何在以 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);
我怎么写这样的东西?
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 的子 class - Both "Porche”和“Car”是Class。除了保时捷,我们还有丰田、宝马、特斯拉……我想通过反射动态检索它们(避免硬编码) "cars" 是 个实例 汽车的列表。
"carType" 是 Type。 如何在以 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);