简体   繁体   中英

C#, use reflection to get each case name in switch

Here's a contrived example of a string literal switch statement:

static string GetStuff(string key)
{
    switch (key)
    {
        case "thing1": return "oh no";
        case "thing2": return "oh yes";
        case "cat": return "in a hat";
        case "wocket": return "in my pocket";
        case "redFish": return "blue fish";
        case "oneFish": return "two fish";
        default: throw new NotImplementedException("The key '" + key + "'  does not exist, go ask your Dad");
    }
}

You get the idea.

What I'd love to do is print each of the literal strings for each of the cases via reflection.

I've not done enough with reflection to know how to do it intuitively. I'm honestly not sure if reflection can do this kind of thing at all.

Can it be done? If so, how?

No, you can't read IL (which is what you are looking for) with Reflection APIs.

The closest you can come is MethodInfo.GetMethodBody ( MethodBody class ) which will give you byte array with IL. To get implementation details of method you need library that reads IL like cecil .

The switch for string is implemented using if or Dictionary based on number of choices - see Are .Net switch statements hashed or indexed? . So if reading IL take that into account.*

Note that you should use some other mechanisms to represent your data rather that trying to read it from compiled code. Ie use dictionary to represent choices as suggested by MikeH's answer .

* info on switch implementation found by Mad Sorcerer .

How about using a Dictionary

  Dictionary<string, string> dict = new Dictionary<string, string>();
  dict.Add("thing1", "oh no");
  dict.Add("thing2", "oh yes");
  //and on and on

  string GetStuff(string key)
  {
    if (dict.ContainsKey(key))
      return dict[key];
    else
      return null; //or throw exception
  }

For your menu:

 void addToMenu()
 {
   foreach (string key in dict.Keys)
   {
     //add "key" to menu
   }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM