【发布时间】:2019-11-23 21:16:36
【问题描述】:
我想知道是否可以优化下面的代码,这样我就不必在每个 case 语句中都有一个“if”语句?减少/最小化代码...
仅供参考 - if 语句在传入生产接口(例如 ARMProduction.WebServiceAWI)和生产对象(例如 new ARMProduction.User())之间切换 而且它们来自不同的接口,所以我认为我不能创建一个接口并通过它。
switch(claimParams.ServiceName) {
case "ARM":
if (_environment.Production)
claimResult = await WebService<ARMProduction.WebServiceAWI>.GetClaim(claimParams, _environment.ARMUrl, _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new ARMProduction.User());
else
claimResult = await WebService<ARMDevelopment.WebServiceAWI>.GetClaim(claimParams, _environment.ARMUrl, _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new ARMDevelopment.User());
break;
case "BW":
if (_environment.Production)
claimResult = await WebService<BWProduction.WebServiceBW>.GetClaim(claimParams, _environment.BWUrl, _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new BWProduction.User());
else
claimResult = await WebService<BWDevelopment.WebServiceBW>.GetClaim(claimParams, _environment.BWUrl, _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new BWDevelopment.User());
break;
case "CS":
if (_environment.Production)
claimResult = await WebService<CSProduction.WebServiceCS>.GetClaim(claimParams, _environment.CSUrl, _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new CSProduction.User());
else
claimResult = await WebService<CSDevelopment.WebServiceCS>.GetClaim(claimParams, _environment.CSUrl, _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new CSDevelopment.User());
break;
}
【问题讨论】:
-
Dictionary<string, Func<Task<ClaimResult>>> -
嗨。你能提供一个更完整的例子吗?
-
你有一个简单的决策树,在当前的样本中,它的大小和复杂性我会保持原样。但是,如果您发现自己通过添加/删除新案例或新环境来不断更改它,那么您可能可以将可更改部分移动到专用结构中,添加和删除它们不需要更改决策逻辑。
标签: c# if-statement interface switch-statement