如何在switch语句中优化if语句

问题描述 投票:0回答:1

我想知道是否有可能在下面优化此代码,这样我就不必在每个case语句中都包含“ if”语句?减少/最小化代码...

FYI-if语句在传递生产接口(例如ARMProduction.WebServiceAWI)和生产对象(例如新的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;
}
c# if-statement interface switch-statement
1个回答
0
投票

如果您真的想减少代码,如@Fabio所述,则可以使用Dictionary。可以使用ServiceName和Production标志将其设置为组合键。

类似:

var claims = new Dictionary<(string, bool), Func<Task<ClaimResult>>>();
claims.Add(("ARM", true), () => WebService<ARMProduction.WebServiceAWI>.GetClaim(claimParams, _environment.ARMUrl, 
        _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new ARMProduction.User()));
claims.Add(("ARM", false), () => WebService<ARMDevelopment.WebServiceAWI>.GetClaim(claimParams, _environment.ARMUrl, 
        _environment.TrustOnlineUsername, _environment.TrustOnlinePassword, new ARMDevelopment.User()));

switch(claimParams.ServiceName) {
case "ARM":
    claimResult = await claims[(claimParams.ServiceName, _environment.Production)].Invoke();
    break;
}
© www.soinside.com 2019 - 2024. All rights reserved.