gpt4 book ai didi

c# - 将多个方法重构为一个通用方法

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:19 26 4
gpt4 key购买 nike

我有以下场景,但有 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);
}
}

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

当我知道所有 4 个版本都具有我需要调用的属性和 repo 方法时,拥有 4 个版本的方法本质上是相同的但具有不同的模型/repos 似乎很愚蠢。

我想我需要使用泛型重构它,但我什至不知道从哪里开始。

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

最佳答案

我同意@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();
}
}

关于c# - 将多个方法重构为一个通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31076969/

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