我如何将 an 转换(或转换,如果转换不可能或不合理)object到它的运行时类型?我可以runtimeType使用反射,但不知道如何List<string>使用property.GetValue- 我知道我可以明确地做as List<String>,但这是一种软代码引擎,其中类型直到运行时才知道。
任何帮助表示赞赏 - 谢谢!(但请寻找代码解决方案,而不是“你不应该这样做......”的答案)
// trimmed-down example class
class Bus { public List<string> Passengers {get;set;} }
// create new instance of class
var obj = new Bus();
// get property value using reflection
var listPropertyName = "Passengers";
var property = GetType(obj).GetProperty($"{listPropertyName}");
var runtimeType = property.PropertyType;
// returns object, but I want List<string> instead
// (or whatever it is; could be different types like T, List<T>, etc.)
var val = property.GetValue(obj);
// doesn't work (assigns null), expects compile-time type
var val = property.GetValue(obj) as runtimeType;
森栏
相关分类