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

One*_*ood 1 .net c# reflection switch-statement

这是一个字符串文字switch语句的人为例子:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

你明白了.

我喜欢做的是通过反射打印每个案例的每个字符串.

我没有做足够的反思,知道如何直观地做到这一点.老实说,我不确定反思是否可以做这种事情.

可以吗?如果是这样,怎么样?

Ale*_*kov 5

不,您无法使用Reflection API读取IL(这是您正在寻找的).

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

switchstring使用实施ifDictionary基于对选择数-见是净switch语句散列或索引?.因此,如果阅读IL考虑到这一点.*

请注意,您应该使用其他一些机制来表示您的数据,而不是尝试从已编译的代码中读取它.即使用字典来表示MikeH的答案所建议的选择.

*Mad Sorcerer发现的实施信息.switch