2015-06-26 39 views
1

我有以下情形,但有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 & AddressId

看來愚蠢的有4個版本的本質上是相同的方法,但不同型號/回購,當我知道所有4個有我需要調用的屬性和回購的方法。

我想我需要重構這個使用泛型,但我甚至不知道從哪裏開始。使用

我已經包括了簡單的例子,我將如何重構4種方法爲一個通用的方法是什麼?

+0

待辦事項'MasterPerson'和'ExceptionPerson'有一個共同的基類? – Lee

+0

沒有他們不,他們都有自己的接口,但是這是爲DI – JsonStatham

+1

我會做一個'Person'普通類,並使用了'MasterPerson'和'ExceptionPerson' –

回答

2

我同意@ausin wernli:IPerson兒童和存儲庫之間

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; } } 
} 

但是緊耦合可能不是你以後,這樣就可以實現在地:

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(); 
    } 
} 
+0

我很讚賞你,先生! –

+0

@的Ondrej-svejdar錯誤無法將類型「T」到「PeopleMapping.Repository.Models.ExceptionPerson」 – JsonStatham

+0

難道不是每個集合即時試圖爲OT使用泛型都有自己的ID,EVPID,mvpId,uvpId問題和emailId,當他們每個人都有不同的Id名時,它如何將T施加給每個人和每個人 – JsonStatham

1

您可以製作一個接口IPerson並在MasterPerson以及ExceptionPerson中執行此操作。定義一個方法,如DeletePerson(int id),這個問題就變得微不足道了。