How to check enum property when property is obtained from dynamic in C #?

Suppose I know that the Color property of an object returns an enumeration that looks like this:

 enum ColorEnum { Red, Green, Blue }; 

and I want to check that for a certain object of an unknown type (which, as I know, has the Color property), Color set to Red . This is what I would do if I knew the type of object:

 ObjectType thatObject = obtainThatObject(); if( thatObject.Color == ColorEnum.Red ) { //blah } 

The problem is that I do not have a reference to the assembly with ColorEnum and do not know the type of object.

So instead, I have the following setting:

 dynamic thatObject = obtainThatObject(); 

and I canโ€™t use because I donโ€™t know the type of the object (and the type of enumeration). How to check Color ?

 if( thatObject.Color.ToString() == "Red" ) { //blah } 

really works, but it looks like the worst example of a load cookie I saw in "The Daily WTF".

How to perform a validation?

+6
source share
3 answers

In the side assembly:

 enum ColorEnum { Red, Green, Blue }; 

We know that Red exists, but nothing about other colors. Therefore, we redefine the enumeration in our assembly only with known values.

 enum KnownColorEnum // in your assembly { Red }; 

Therefore, we can parse:

 public static KnownColorEnum? GetKnownColor(object value) { KnownColorEnum color; if (value != null && Enum.TryParse<KnownColorEnum>(value.ToString(), out color)) { return color; } return null; } 

Examples:

 // thatObject.Color == ColorEnum.Red // or // thatObject.Color == "Red" if (GetKnowColor(thatObject.Color) == KnownColorEnum.Red) // true { } // thatObject.Color == ColorEnum.Blue if (GetKnowColor(thatObject.Color) == KnownColorEnum.Red) // false { } 
+1
source

Just analyze the Color property for your enumeration first

 if ((ColorEnum) Enum.Parse(typeof (ColorEnum), thatObject.Color.ToString()) == ColorEnum.Red) { // do something } 
+2
source

One of the possible (unorthodox) methods is to make your dynamic object (whatever it may be) be ExpandoObject (using this extension method):

  public static dynamic ToDynamic(this object value) { IDictionary<string, object> expando = new ExpandoObject(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) expando.Add(property.Name, property.GetValue(value)); return expando as ExpandoObject; } 

Convert the resulting object:

 var obtainedObject = (object)obtainThatObject(); var myexpando = obtainedObject.ToDynamic(); // now you have an ExpandoObject 

So you can get the properties in an IDictionary

 IDictionary<string, object> dictionary= (IDictionary<string, object>) myexpando; if(dictionary.ContainsKey("Color")) { var myValue = dictionary["Color"]; string color = myValue.ToString(); if(color == "Green") { // blah } } 

Going this way, you do not need to worry about which particular object ...

0
source

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


All Articles