vendredi 26 avril 2019

C# how to cast object to runtime type?

How can I cast (or convert, if cast not possible or reasonable) an object into its runtime type? I can get runtimeType using reflection, but can't figure out how to get List<string> using property.GetValue - I know that I could explicitly do as List<String> but this is for a sort-of soft-code engine where the types are not known until runtime.

Any help is appreciated - thanks! (but looking for code solutions please, not "you shouldn't do it this way..." answers)

// 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 className = "Bus";
var assemblyName = "MyAssembly";
var listPropertyName = "Passengers";
var property = GetType(obj).GetProperty($"{listPropertyName}");
var runtimeType = Type.GetType($"{obj.GetType().FullName},{assemblyName}");

// returns object, but I want List<string> instead 
// (or whatever it is; could be different types like T, List<T>, etc.
property.GetValue(obj);

// doesn't work, expects compile-time type
property.GetValue(obj) as runtimeType; 





Aucun commentaire:

Enregistrer un commentaire