How to clean up if else series

后端 未结 4 596
有刺的猬
有刺的猬 2020-12-01 23:10

Work in C#, want to reduce if else series, entity have two property FromServiceID and ToServiceID ,suppose my ServiceClass instanc

4条回答
  •  日久生厌
    2020-12-01 23:58

    Use a Dictionary. Something like this:

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

    An example of how using it:

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

提交回复
热议问题