C # Dynamic Object - Enum Value

I have a dynamic object (C # 4.0) in which I want to set the Enum value for a property dynamically, but I have no assembly reference for this type. Any idea on how to do this / is it possible to do this?

dynamic vehicle = myObject; vehicle.AddTires(); // working vehicle.ConfigureEngine(); //working vehicle.seat="Leather";//working //Enum needs to be set for the Make vehicle.Make = Manufacturer.Toyota; // how to do this? 
+4
source share
2 answers

If c.Make always matters (for example, its type is Manufacturer and not Manufacturer? Or the property does not exist at all before setting it):

 c.Make = Enum.Parse(c.Make.GetType(), "Toyota"); 

If this does not work for you as it is, to use this approach you need to somehow get a reference to the Manufacturer type. How complicated this is depends on how your dynamic type is configured. Another approach (for example, if it is Manufacturer? And may be null), you may need to use reflection to get the Make property to find out what type it is.

+12
source

Enum.Parse() has an object return type, however you can drop the returned object to dynamic to make it look at the actual runtime type.

 vehicle.Make = (dynamic)Enum.Parse(vehicle.Make.GetType(), "Toyota"); 
+2
source

Source: https://habr.com/ru/post/1440978/


All Articles