c# - 在 C# 中设计可配置的返回值

标签 c# .net-4.5

<分区>

我收到了一份电子表格,其中包含可能的返回代码及其来自第三方网络服务的描述。它们看起来像这样(简化):

 Code       Description
 M1         Some description of M1
 M2         Some description of M2
 M3         Some description of M3
 M4         Some description of M4
 P1         Some description of P1
 P2         Some description of P2
 N1         Some description of N1
 N2         Some description of N2

在上面的列表中,M 代码属于匹配,P 代码属于部分匹配,I 代码属于不匹配

在 C# 函数中,这些返回值由 switch case 处理,如下所示:

...
switch(returncode)
{
case "M1":
case "M2":
case "M3":
case "M4":
     DoSomethingForMatch(ReturnCodeDescription); 
     break;
case "P1":
case "P2":
case "P3":
case "P4": 
     DoSomethingForPartialMatch(ReturnCodeDescription);
     break;
case "N1":
case "N2": 
default:
     DoSomethingForNoMatch(ReturnCodeDescription); 
     break;
}

虽然返回码看起来很相似,但没有命名约定。将来可能会有其他格式不同的返回码。但它们仍属于以下三类之一:匹配、部分匹配和不匹配。

以防将来有新的返回码,采用这种设计,我必须更新代码并重新构建、重新部署等。

必须有比像这样在代码中硬编码返回值更好的方法来做到这一点。我想就如何以可配置、可扩展的方式执行此操作征求您的意见。将所有可能的代码和描述保存在数据库表中是完成此操作的最佳方法吗? 谢谢。

最佳答案

为什么不只检查第一个字符呢?

switch(returncode[0])
{
    case 'M':
         DoSomethingForMatch(ReturnCodeDescription); 
         break;
    case 'P':
         DoSomethingForPartialMatch(ReturnCodeDescription);
         break;
    case 'N': 
    default:
         DoSomethingForNoMatch(ReturnCodeDescription); 
         break;
}

关于c# - 在 C# 中设计可配置的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686838/

相关文章:

c# - 如何使用 LINQ 将数组转换为字典

c# - 单一 View ,多个 View 模型 - 避免绑定(bind)错误?

c# - ASP.Net Web 应用程序 dll 加载问题

c# - PowerShell 脚本表达式或语句中出现错误 "Unexpected token ' h'。字符串缺少终止符 :"

c# - BufferBlock 和 TPL 数据流行为

c# - WPF 径向进度条/仪表(即电池表)

wpf - WeakEventManager 和 DependencyPropertyChangedEventArgs

c# - volatile 字段 : How can I actually get the latest written value to a field?

c# - Application_AuthenticateRequest 和 FormsAuthentication_OnAuthenticate 有什么区别

vb.net - 日期比较 myDateTime.Equals(DateTime.MinValue) 在 VB.Net 中不起作用