c# - 如何在 C# 中重用外包装迭代代码?
问题描述
我想多次重用相同的迭代代码,我只想定义一次。在迭代中,可以有各种不同的方法和各种不同的输入。这如何在 C# 中完成?
我不关心性能。我主要关心的是“不重复相同的代码”和可读性。
请参阅以下伪代码。我想DoMainStuff()
用看起来像的东西替换DoMainStuff_Desired()
。
(到目前为止,我一直在尝试用代表解决它。它大大降低了可读性。请参阅第二个附加代码。)
public class Class1
{
public void DoStuff1(int x,int y)
{
//Doing something.
}
public void DoStuff2(int x, int y, string bla)
{
//Doing something.
}
public void DoStuffx(int x, int y, "whatevertype" ble, "maybe more inputs")
{
//This represents multiple methods that do stuff.
//They can have different number of inputs of different types.
//I do not know all of them at this point.
}
public void DoMainStuff()
{
//I do not want to repeat same code for iteration multiple times.
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
DoStuff1(x, y);
}
}
//Something happening that prevents me having it in the same loop.
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
DoStuff2(x, y, "somestring");
}
}
//Something happening that prevents me having it in the same loop.
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
DoStuffx(x, y, "somestring", 50f, "anotherstring");
}
}
}
public void DoMainStuff_Desired()
{
//This is how I want to have it. (Something similar)
WrappedInIteration(DoStuff1(x, y));
//Something happening that prevents me having it in the same loop.
WrappedInIteration(DoStuff2(x, y, "somestring"));
//Something happening that prevents me having it in the same loop.
WrappedInIteration(DoStuffx(x, y, "somestring", 50f, "anotherstring"));
}
}
这是我与代表一起尝试过的。我不喜欢这个解决方案,因为我必须修改 DoStuffx 方法以具有与委托相同的参数签名。(params object[] args) -> 这个签名允许任何输入,但它很难阅读,因为各种不同的 DoStuffx 方法实际需要哪些输入并不明显。
public class Class1
{
public void DoStuff1(params object[] args)
{
//Doing something.
}
public void DoStuff2(params object[] args)
{
//Doing something.
}
public void DoStuffx(params object[] args)
{
//This represents multiple methods that do stuff.
//They can have different number of inputs of different types.
//I do not know all of them at this point.
}
public void DoMainStuff()
{
WrappedInIteration_DelegateVersion(DoStuff1);
//Something happening that prevents me having it in the same loop.
WrappedInIteration_DelegateVersion(DoStuff2, "somestring");
//Something happening that prevents me having it in the same loop.
WrappedInIteration_DelegateVersion(DoStuffx, "somestring", 50f, "anotherstring");
}
public delegate void DelegateForDoStuff(params object[] args);
public void WrappedInIteration_DelegateVersion(DelegateForDoStuff DoStuff, params object[] args)
{
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
DoStuff(x,y, args);
}
}
}
}
解决方案
推荐阅读
- python - 求解 Mod 多个方程
- python - 在复杂的嵌套字典/列表中搜索键、值对
- python - 为什么softmax分类器梯度除以批量大小(CS231n)?
- java - 使用 Itext PDF 创建 PDF 文件时出现空白页
- java - 我们可以将背包问题转换为对数时间吗?
- yacc - byacc/j 和 jflex 中的错误恢复使用 yacc 中的错误标记
- python - 在python中使用另一个函数的结果
- flutter - Flutter:如何使用 setter 重置值
- java - 有没有办法解决':app:checkDebugDuplicateClasses'。在颤振?
- php - 找不到类“数据库\播种机\”的问题