[英]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);
}
在这里, 保时捷是一个汽车的子类 - “ 保时捷 ”和“ 汽车 ”都是阶级 。 除了保时捷之外,我们还有Toyata,宝马,特斯拉...我想通过反射动态检索它们(避免硬编码) “汽车”是一系列汽车实例 。
“ carType ”是Type 。 如何在JsonConvert.DerserializeObject中使用“carType”将List作为参数?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.