gpt4 book ai didi

c# - 如何将这两种相似的方法合二为一?

转载 作者:行者123 更新时间:2023-11-30 19:02:37 25 4
gpt4 key购买 nike

下面的方法只是彼此相反。我怀疑我可以将逻辑组合成一种方法。我宁愿避免反射。是否可以将它们结合起来并保持可读性?

    private void btnAdd_Click(object sender, EventArgs e)
{
LabEntity selectedItem = bindingSource1.Current as LabEntity;
selectedLabsData.Add(selectedItem);
availableLabsData.Remove(selectedItem);
}

private void btnRemove_Click(object sender, EventArgs e)
{
LabEntity selectedItem = bindingSource2.Current as LabEntity;//new binding source
availableLabsData.Add(selectedItem);//called Add instead of remove
selectedLabsData.Remove(selectedItem);//called Remove instead of Add
}

最佳答案

您可以将逻辑提取到辅助方法中:

private void ListFixup(object entity, List<Item> addList, List<Item> removeList)
{
LabEntity selectedItem = entity as LabEntity;
// don't forget your error checking here

addList.Add(selectedItem);
removeList.Remove(selectedItem);
}

private void btnAdd_Click(object sender, EventArgs e)
{
ListFixup(bindingSource1.Current, selectedLabsData, availableLabsData);
}

private void btnRemove_Click(object sender, EventArgs e)
{
ListFixup(bindingSource2.Current, availableLabsData, selectedLabsData);
}

我不确定这是否有助于提高可读性,但它确实减少了代码重复。

关于c# - 如何将这两种相似的方法合二为一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10919887/

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