gpt4 book ai didi

c# - 如何消除重复代码?

转载 作者:太空狗 更新时间:2023-10-29 17:45:26 24 4
gpt4 key购买 nike

我有以下代码,我想以一种代码重复最少的方式编写它。

if (Categories != null)
{
bool flag=false;
foreach (dynamic usableCat in Category.LoadForProject(project.ID))
{
foreach (dynamic catRow in Categories)
{
if (usableCat.ID == catRow.ID)
flag = true;
}
if (!flag)
{
int id = usableCat.ID;
Category resolution = Category.Load(id);
resolution.Delete(Services.UserServices.User);
}
}
}
if (Priorities != null)
{
bool flag = false;
foreach (dynamic usableCat in Priority.LoadForProject(project.ID))
{
foreach (dynamic catRow in Priorities)
{
if (usableCat.ID == catRow.ID)
flag = true;
}
if (!flag)
{
int id = usableCat.ID;
Priority resolution = Priority.Load(id);
resolution.Delete(Services.UserServices.User);
}
}
}

请注意,Category 和 priority 没有包含 ID 的公共(public)基类型或接口(interface)。

最佳答案

void DeleteUsable<Ttype>(IEnumerable<Ttype> usables, IEnumerable<Ttype> collection, Func<int, Ttype> load)
{
bool flag = false;
foreach (dynamic usableCat in usables)
{
foreach (dynamic catRow in collection)
{
if (usableCat.ID == catRow.ID)
flag = true;
}
if (!flag)
{
int id = usableCat.ID;
Ttype resolution = load(id);
resolution.Delete(Services.UserServices.User);
}
}
}

编辑:调用它:

if (Categories != null) 
DeleteUsable(Category.LoadForProject(project.ID), Categories, Categoriy.Load);
if (Priorities != null)
DeleteUsables(Priority.LoadForProject(project.ID), Priorities, Priority.Load);

关于c# - 如何消除重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253023/

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