gpt4 book ai didi

c# - if else系列如何清理

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:59 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com