如何在switch语句中确定当前的大小写?(How to determine the current case in a switch statement?)

是否可以确定当前正在评估哪种情况? 像这个示例代码:

const int one = 1; const int two = 2; int current_num = 1; switch (current_num){ case one: case two: WriteLine(current_case) //outputs 'one' break; }

我相信一旦我开始使用WriteLine ,我可能会变得棘手并使用字典或其他东西来查找current_num ,但是可能有一种内置的方法来获取当前正在评估的当前案例的名称。

编辑 :简答,这是不可能的。 查看JonSkeet的答案,找出合理的替代方案。

Is is possible to determine which case is currently being evaluated? Something like this example code:

const int one = 1; const int two = 2; int current_num = 1; switch (current_num){ case one: case two: WriteLine(current_case) //outputs 'one' break; }

I believe I could get tricky and use a dictionary or something to look up the current_num once I've begun to WriteLine, but there could be a built-in way to get the name of the current case currently being evaluated.

edit: Short answer, it's not possible. Check out JonSkeet's answer for a plausible alternative.

最满意答案

目前还不是很清楚你要做什么,但我怀疑你的恩赐会更好:

enum Foo { One = 1, Two = 2, Three = 3 } ... int someValue = 2; Foo foo = (Foo) someValue; Console.WriteLine(foo); // Two

你仍然可以在case语句中使用它:

switch (foo) { case Foo.One: case Foo.Two: Console.WriteLine(foo); // One or Two, depending on foo break; default: Console.WriteLine("Not One or Two"); }

It's not really clear what you're trying to do, but I suspect you'd be better off with an enum:

enum Foo { One = 1, Two = 2, Three = 3 } ... int someValue = 2; Foo foo = (Foo) someValue; Console.WriteLine(foo); // Two

You can still use this within a case statement:

switch (foo) { case Foo.One: case Foo.Two: Console.WriteLine(foo); // One or Two, depending on foo break; default: Console.WriteLine("Not One or Two"); }

更多推荐