我该如何将一个
感谢任何帮助 - 谢谢!(但请提供代码解决方案,而非“你不应该这样做…”的答案)
object
转换为其运行时类型(如果无法转换,可以转换成另一种类型)? 我可以使用反射获取runtimeType
,但是无法强制使用property.GetValue
获取List<string>
- 我知道我可以显式地使用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;
var
与JavaScript中的相同(这显然是不正确的),或者与dynamic
相同(这也是不正确的)...澄清你真正想要对属性值做什么可能有助于可能的解决方案(动态调用泛型方法,dynamic
,纯反射,代码生成等)。 - Alexei Levenkovproperty
的运行时类型不一定与runtimeType
相同... - Alexei Levenkov