使用“开关”;与资源文件中的字符串
我的资源(.resx)文件中有一堆字符串。我试图直接将它们用作 switch 语句的一部分(请参阅下面的示例代码)。
class Test
{
static void main(string[] args)
{
string case = args[1];
switch(case)
{
case StringResources.CFG_PARAM1: // Do Something1
break;
case StringResources.CFG_PARAM2: // Do Something2
break;
case StringResources.CFG_PARAM3: // Do Something3
break;
default:
break;
}
}
}
我查看了一些解决方案,其中大多数似乎建议我需要将它们声明为我个人不喜欢的 const string
。 我喜欢这个问题的投票最高的解决方案: 在 switch 语句中使用字符串集合。但随后我需要确保资源文件中的 enum
和 string
绑定在一起。我想知道一种巧妙的方法。
编辑: 在研究如何使用时还发现这个很好的答案 >操作
:
I have a bunch of strings in my resource(.resx) file. I am trying to directly use them as part of switch statement (see the sample code below).
class Test
{
static void main(string[] args)
{
string case = args[1];
switch(case)
{
case StringResources.CFG_PARAM1: // Do Something1
break;
case StringResources.CFG_PARAM2: // Do Something2
break;
case StringResources.CFG_PARAM3: // Do Something3
break;
default:
break;
}
}
}
I looked at some of the solutions, most of them seem to suggest that I need to declare them as const string
which I personally dislike.
I liked the top voted solution for this question: using collection of strings in a switch statement. But then I need to make sure that my enum
and strings
in resource file are tied together. I would like to know a neat way of doing that.
Edit:
Also found this great answer while researching how to use Action
:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Dictionary
。您为字典中的每个字符串放置一个Action
(方法的委托)并搜索它。作为旁注,如果
Method1
已经是Action
或void Method1()
方法(没有参数,没有返回值),您可以做You could use a
Dictionary<string, Action>
. You put anAction
(a delegate to a method) for each string in the Dictionary and search it.As a sidenote, if
Method1
is already anAction
or avoid Method1()
method (with no parameters and no return value), you could do你不能那样做。编译器必须能够计算这些值,这意味着它们必须是文字或常量。
You can't do that. The compiler must be able to evaluate the values, which means that they need to be literals or constants.
我自己刚刚遇到这个问题,虽然这篇文章很旧,但我想我应该为其他“Google 员工”分享我的简单解决方案...我选择将
switch...case
更改为多个if(...) elseif
绝对不如
switch...case
漂亮,但对我有用。I just came across this problem myself, and although this post is old, I thought I'd share my simple solution for other "Googlers"... I opted to change the
switch...case
to multipleif(...) elseif
Definitely not as pretty as
switch...case
but has worked for me.