这是一个字符串文字 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");
}
}
你明白了。
我想做的是通过反射为每个案例打印每个文字字符串。
我在反射(reflection)方面做的还不够多,不知道如何凭直觉去做。老实说,我不确定反射是否可以做这种事情。
可以吗?如果是,怎么办?
最佳答案
不,您不能使用反射 API 读取 IL(这正是您要寻找的)。
最接近的是 MethodInfo.GetMethodBody
(MethodBody class),它将为您提供带 IL 的字节数组。要获取方法的实现细节,您需要读取 IL 的库,如 cecil 。
string
的switch
是根据选择的数量使用if
或Dictionary
实现的- 参见 Are .Net switch statements hashed or indexed? 。因此,如果阅读 IL,请考虑到这一点。*
请注意,您应该使用其他一些机制来表示您的数据,而不是尝试从编译代码中读取它。 IE。按照 MikeH's answer 的建议使用字典来表示选择。
* 关于 Mad Sorcerer 发现的 switch
实现的信息。
关于C#,使用反射获取switch中的每个case名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26747477/