gpt4 book ai didi

C# 当差异出现在循环中间时如何避免代码重复

转载 作者:行者123 更新时间:2023-12-02 01:26:47 25 4
gpt4 key购买 nike

目前我有两个这样的函数

GenerateDocumentA(DocumentA docA)
{
OpenDocumentCode();
for (int i = 0; i < pageCount; i ++)
{
// some common per page code, var page = xxx
SpecificCodeA(docA, page, i);
}
CloseDocumentCode();
}

GenerateDocumentB(DocumentB docB)
{
OpenDocumentCode();
for (int i = 0; i < pageCount; i ++)
{
// some common per page code, var page = xxx
SpecificCodeB(docB, page, i);
}
CloseDocumentCode();
}

我尝试删除重复代码并看到了这个答案

https://codereview.stackexchange.com/questions/18379/how-to-remove-code-duplication-that-difference-only-a-few-lines

遇到一个问题,我不知道如何将变量从两个地方传递到 SpecificCode()

GenerateDocument(Action SpecificCode)
{
OpenDocumentCode();
for (int i = 0; i < pageCount; i ++)
{
// some common per page code, var page = xxx
SpecificCode(); // How to pass the current page / page index
}
CloseDocumentCode();
}

GenerateDocumentA(DocumentA docA)
{
GenerateDocument( () => { } ) // how to also pass the DocumentA docA
}

我的问题是:我如何定义并将 SpecificCode() 传递给 GenerateDocument() 公共(public)代码,知道 SpecificCode() 采用GenerateDocumentA()GenerateDocument() 中的变量作为参数

最佳答案

GenerateDocument(Action<int,int> todo)
{
OpenDocumentCode();
for (int i = 0; i < pageCount; i ++)
{
// some common per page code, var page = xxx
todo(page,i);
}
CloseDocumentCode();
}

用例:

DocumentA docA;
GenerateDocument((int page, int i)=>
{
SpecificCodeA(docA, page, i);
});

DocumentB docB;
GenerateDocument((int page, int i)=>
{
SpecificCodeB(docB, page, i);
});

关于C# 当差异出现在循环中间时如何避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74400382/

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