C#,使用反射来获取switch中的每个case名称

本文关键字:名称 case switch 获取 反射 | 更新日期: 2023-09-27 18:29:03

下面是一个字符串文字切换语句的人为示例:

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");
    }
}

你明白了。

我想做的是通过反射打印每个案例的每个文本字符串。

我在反思方面做得还不够,不知道如何凭直觉去做。老实说,我不确定反思是否能做到这一点。

能做到吗?如果是,如何?

C#,使用反射来获取switch中的每个case名称

不,您无法使用反射API读取IL(这正是您想要的)。

最接近的是MethodInfo.GetMethodBody(MethodBody类),它将为您提供带有IL的字节数组。要获得方法的实现细节,您需要像cecil一样读取IL的库。

stringswitch是根据选择的数量使用ifDictionary实现的-请参阅.Net开关语句是散列的还是索引的?。因此,如果阅读IL,请将其考虑在内。*

请注意,您应该使用一些其他机制来表示数据,而不是尝试从编译的代码中读取数据。也就是说,按照MikeH的回答,用字典来表示选择。

*关于疯狂魔法师发现的switch实现的信息

使用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
  }

对于您的菜单:

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