c# - if else系列如何清理

标签 c# coding-style

在 C# 中工作,想减少 if else 系列,实体有两个属性 FromServiceIDToServiceID ,假设我的 ServiceClass 实例有以下信息.如何清理波纹管代码?任何类型的建议都将被接受。

entity= new ServiceClass();
entity.FromServiceID=3
entity.ToServiceID=1

if (entity.FromServiceID == 1)
{
    entity.1KWithdrawal();
}
else if (entity.FromServiceID == 2)
{
    entity.10KWithdrawal();
}
else if (entity.FromServiceID == 3)
{
    entity.BTWithdrawal();
}           
if (entity.ToServiceID == 1)
{
    entity.1KDeposit();
}
else if (entity.ToServiceID == 2)
{
    entity.10KDeposit();
}
else if (entity.ToServiceID == 3)
{
    entity.BTDeposit();
}


public class ServiceClass
{ 

    public int FromServiceID { get; set; }
    public int ToServiceID { get; set; }

    public void 1KWithdrawal()
    { Console.WriteLine("One_KWithdrawal"); }

    public void 10KWithdrawal()
    { Console.WriteLine("Ten_KWithdrawal"); }

    public void BTWithdrawal()
    { Console.WriteLine("BTWithdrawal"); }

    public void 1KDeposit()
    { Console.WriteLine("One_KDeposit"); }

    public void 10KDeposit()
    { Console.WriteLine("Ten_KDeposit"); }

    public void BTDeposit()
    { Console.WriteLine("Ten_KDeposit"); }
}

最佳答案

使用 Dictionary .像这样:

Dictionary<int, ServiceClass> dictionary = new Dictionary<int, ServiceClass>()
{
    {1,  new ServiceClass()},
    {2,  new ServiceClass()},
    {3,  new BTWithdrawal()},//assume BTWithdrawal inherits from ServiceClass
};

如何使用它的示例:

ServiceClass value=new ServiceClass();
value.FromServiceId=1;
value.ToServiceId = 2;
dictionary.TryGetValue(value.FromServiceId, out value);
//or dictionary.TryGetValue(value.ToServiceId, out value);
if (value != null) MessageBox.Show(value.Id.ToString());

关于c# - if else系列如何清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505261/

相关文章:

java - switch 语句 vs if 语句,哪个对性能更好?

loops - 为什么使用 for 循环而不是 while 循环?

c# - 唯一标识 U 盘

c# - 比 Marshall.QueryInterface 更简洁的编码方式?

c# - 如何使 Html.CheckBoxFor() 在字符串字段上工作?

language-agnostic - 您是否遇到过三层间接寻址的任何原因?

c++ - 使用 #define 指令作为代码的 "part",而不是在文件顶部

c# - "Runtime error Exception has been thrown by the target of an invocation"来自脚本任务

c# - 在AutoFac容器中针对 View 注册WPF ViewModel的最佳方法是什么?

math - 在 switch case 语句中检测 2 个变量值的 4 个排列