How to get through a static class of constants?

Instead of using the Switch statement, as shown in the code below, is there an alternative way to check if foo.Type any of the constants in the Parent.Child class?

The goal is to look at all the constant values ​​to see if foo.Type match, instead of specifying each constant as case .

Parent class:

 public class Parent { public static class Child { public const string JOHN = "John"; public const string MARY = "Mary"; public const string JANE = "Jane"; } } 

code:

 switch (foo.Type) { case Parent.Child.JOHN: case Parent.Child.MARY: case Parent.Child.JANE: // Do Something break; } 
+6
source share
3 answers

Using Reflection , you can find all the constant values ​​in the class:

 var values = typeof(Parent.Child).GetFields(BindingFlags.Static | BindingFlags.Public) .Where(x => x.IsLiteral && !x.IsInitOnly) .Select(x => x.GetValue(null)).Cast<string>(); 

Then you can check if the value contains something:

 if(values.Contains("something")) {/**/} 
+5
source

While you can scroll through constants declared in the same way as using reflection (as other answers show), this is not ideal.

It would be much more efficient to store them in some kind of enumerable object: an array, a list, an ArrayList, whatever it best suits your requirements.

Sort of:

 public class Parent { public static List<string> Children = new List<string> {"John", "Mary", "Jane"} } 

Then:

 if (Parent.Children.Contains(foo.Type) { //do something } 
+1
source

You can use reflection to get all the constants of a given class:

 var type = typeof(Parent.Child); FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); var constants = fieldInfos.Where(f => f.IsLiteral && !f.IsInitOnly).ToList(); var constValue = Console.ReadLine(); var match = constants.FirstOrDefault(c => (string)c.GetRawConstantValue().ToString() == constValue.ToString()); 
0
source

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


All Articles