如何在 switch 语句中重构以下 switch?
关于如何重构以下内容的任何想法:
private string GetErrorText(ErrorType type, int error, string id)
{
string errorMessage = string.Empty;
switch (type)
{
case ErrorType.Generic:
switch (error)
{
case (int)ErrorType.One:
errorMessage = string.Format("Generic Error {0}",id);
break;
case (int)ErrorType.Two:
errorMessage = "Generic Error 2.";
break;
}
break;
case ErrorType.NonGeneric:
switch (error)
{
case (int)NonGenericError.One:
errorMessage = "One";
break;
case (int)NonGenericError.Two:
errorMessage = "Two";
break;
case (int)NonGenericError.Three:
errorMessage = "Three";
break;
case (int)NonGenericError.Four:
errorMessage = "Four"
break;
}
break;
}
return errorMessage;
}
我知道我可能可以只返回字符串而不是使用break关键字。听说可以把这个放进字典里就可以完全避免切换了。另外,switch语句可以组合吗?即使我需要将多个参数传递给 string.Format 方法,也会发生什么情况。现在,只需要一个?
Any ideas on how to refactor the following:
private string GetErrorText(ErrorType type, int error, string id)
{
string errorMessage = string.Empty;
switch (type)
{
case ErrorType.Generic:
switch (error)
{
case (int)ErrorType.One:
errorMessage = string.Format("Generic Error {0}",id);
break;
case (int)ErrorType.Two:
errorMessage = "Generic Error 2.";
break;
}
break;
case ErrorType.NonGeneric:
switch (error)
{
case (int)NonGenericError.One:
errorMessage = "One";
break;
case (int)NonGenericError.Two:
errorMessage = "Two";
break;
case (int)NonGenericError.Three:
errorMessage = "Three";
break;
case (int)NonGenericError.Four:
errorMessage = "Four"
break;
}
break;
}
return errorMessage;
}
I know I can probably just return the string instead instead of using the break keyword. I heard that I can put this into a dictionary to completely avoid the switch. Also, can the switch statements be combined? And what happens in the even that I need to pass more than one argument to the string.Format method. Right now, it only takes one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将字符串值与枚举关联的一种相当常见的方法是使用自定义属性,并在运行时通过反射查找它。这是一个很好的解释。
当然,在实践中使用反射会比仅使用条件慢。
A fairly common way to associate a string value with an
enum
is to use a custom attribute, and look it up at runtime with reflection. Here's a good explanation.Of course, using reflection will be slower in practice than just using conditionals.
一个明显的观察结果是,“type”的值并不重要 - 您只需在“error”上设置一个开关即可。
string.Format 根据需要接受尽可能多的参数,例如
One obvious observation is that the value of "type" doesn't matter - you can just have a single switch on "error".
string.Format takes as many arguments as needed, e.g.
为什么不呢?
和
编辑
如果真正的代码很简单,就像你可以做的例子一样
Why not?
and
EDIT
if the real code is a simple as the example you could do