如何清理其他系列 [英] How to clean up if else series

查看:78
本文介绍了如何清理其他系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中工作,如果要减少其他系列,则实体具有两个属性 FromServiceID ToServiceID ,假设我的 ServiceClass 实例具有波纹管信息。如何清除波纹管代码?

Work in C#, want to reduce if else series, entity have two property FromServiceID and ToServiceID ,suppose my ServiceClass instance have bellow information.How to clean up bellow code? any type of suggestion will be acceptable.

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 。这样的事情:

Use a Dictionary. Something like this:

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());

这篇关于如何清理其他系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆