将多个方法重构为一个通用方法

时间:2015-06-26 15:27:41

标签: c#

我有以下场景,但有4种方法和调用而不是2。

RemoveNoLongerRequiredFromExceptions(newPeople, masterPeople);
RemoveNoLongerRequiredFromMaster(newPeople, exceptionPeople);

public void RemoveNoLongerRequiredFromMaster(List<NewPerson> newPeople,
  List<MasterPerson> masterPeople)
{
  var noLongerNewPeople = masterPeople.Where(a => !newPeople.Any(b => 
    a.PerId == b.PerId && a.AddressId == b.AddressId));

  foreach (var item in noLongerNewPeople )
  {                
    _masterRepository.DeleteMasterPerson(item.MvpId);
  }            
}

public void RemoveNoLongerRequiredFromExceptions(List<NewPerson> newPeople, 
  List<ExceptionPerson> exceptionPeople)
{
  var noLongerNewPeople = exceptionPeople.Where(a => !newPeople.Any(b => 
    a.PerId == b.PerId && a.AddressId == b.AddressId));

  foreach (var item in noLongerNewPeople )
  {
    _exceptionRepository.DeleteExceptionPerson(item.EvpId);                
  }
}

这些方法唯一不同的是第二个输入参数,但是这些类型中的每一个都具有所需的属性PerId&amp; AddressId

当我知道所有4个版本都有我需要调用的属性和repo方法时,似乎有4个版本基本上是相同的方法,但有不同的模型/回购。

我想我需要使用泛型来重构这一点,但我甚至不知道从哪里开始。

使用我所包含的简单示例,我如何将4种方法重构为一种通用方法?

2 个答案:

答案 0 :(得分:2)

我同意@ausin wernli:

public interface IPerson
{
  int AddressId { get; }
  int PerId { get; }
  int UniqueEntityId { get; }
}

public MasterPerson : IPerson {
  public int UniqueEntityId { get { return MvpId; } }
}
public ExceptionPerson : IPerson {
  public int UniqueEntityId  { get { return EvpId; } }
}

然而,IPerson子项与存储库之间的紧密耦合可能不是您所追求的,因此您可以通过以下方式实现:

public void RemoveNoLongerRequired<T>(List<NewPerson> newPeople,
  List<T> masterPeople) where T : IPerson
{
  var noLongerNewPeople = masterPeople.Where(a => !newPeople.Any(b =>
    a.PerId == b.PerId && a.AddressId == b.AddressId));

  foreach (var item in noLongerNewPeople)
  {
    if (typeof(T) == typeof(MasterPerson))
    {
      _masterRepository.DeleteMasterPerson(item.UniqueEntityId);
      continue;
    }
    if (typeof(T) == typeof(ExceptionPerson))
    {
      _exceptionRepository.DeleteExceptionPerson(item.UniqueEntityId);
      continue;
    }
    throw new NotImplementedException();
  }
}

答案 1 :(得分:1)

您可以创建一个界面IPerson,并在MasterPersonExceptionPerson中实现此功能。定义一个方法,例如DeletePerson(int id),这个问题变得微不足道。