我想多次重复使用相同的迭代代码,并且只定义一次。在迭代内,可以有各种不同的方法和各种不同的输入。如何在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, x, y);
//Something happening that prevents me having it in the same loop.
WrappedInIteration_DelegateVersion(DoStuff2, x, y, "somestring");
//Something happening that prevents me having it in the same loop.
WrappedInIteration_DelegateVersion(DoStuffx, x, y, "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(args);
}
}
}
}
您可以使用Linq的Zip运算符从2个或多个枚举中创建一个枚举,然后对该枚举进行处理。