我有一个条件让我们假设 Animal = {Dog,Cat,Elephant}
现在我想创建一个带有 if 条件的 for 循环(不是简单的 for 循环),在这个 for 循环中我根据动物类型做了一些代码,例如:
for(int i=0;i<100;i++)
{
if(some conditions on i)
{
for(int j =0;j<100;j++)
{
if(some condition on j)
{
switch(animaltype)
{
case Dog: //call function 1
case Cat: //call function 2
case Elephant: //call function 3
}
}
}
}
}
所以为了在大循环的情况下进行性能优化,我在 for 循环之外制作了 switch-case 所以代码变成了这样的:
switch (animaltype)
{
case Dog :
for(int i=0;i<100;i++)
{
if(some conditions on i)
{
for(int j =0;j<100;j++)
{
if(some condition on j)
{
//call function 1
}
}
}
}
//-------------
case Cat :
for(int i=0;i<100;i++)
{
if(some conditions on i)
{
for(int j =0;j<100;j++)
{
if(some condition on j)
{
//call function 2
}
}
}
}
//----------------------
case Elephant :
for(int i=0;i<100;i++)
{
if(some conditions on i)
{
for(int j =0;j<100;j++)
{
if(some condition on j)
{
//call function 3
}
}
}
}
}
这里的问题是我重复了代码 3 次(或作为案例数),这违反了软件设计的一次且仅一次原则。
我试图传递一个委托(delegate),但我应该调用的 3 个函数有不同的参数,谁能告诉我一个巧妙的解决方案?
编辑 我所说的“不同参数”是指它们不采用相同数量的参数。 例如:
function1(string s,int age)
function2(float height,bool CanMove)
function3(int legs,string name,string place)
请您参考如下方法:
尝试这样的事情:
void ExecuteLoop(Func callback)
{
for(int i=0;i<100;i++)
{
if(some conditions on i)
{
for(int j =0;j<100;j++)
{
if(some condition on j)
{
callback();
}
}
}
}
}
switch (animaltype)
{
case Dog:
ExecuteLoop(dogCallback);
break;
case Cat:
ExecuteLoop(catCallback);
break;
case Elephant:
ExecuteLoop(elephantCallback);
break;
}
这将允许您将循环合并为一个方法,同时改变实际执行的内容。当你说时不清楚:
...but the 3 functions that I supposed to call have different arguments...
你是什么意思。我假设以下两件事之一:
- 您打算调用的三个方法将不同的值作为参数传递。
或
- 您打算调用的三个方法有不同的数量 传递给它们的参数。
无论哪种方式,您都可以在之前的解决方案的基础上解决这个问题。像这样:
switch (animaltype)
{
case Dog:
ExecuteLoop(() => { dogCallback(1, 2, 3); });
break;
case Cat:
ExecuteLoop(() = > { catCallback( "argument 1", "arg 2" ); });
break;
case Elephant:
ExecuteLoop(() => { elephantCallback(i, j, k); });
break;
}
这使用 lambdas不接受任何参数(因此符合 ExecuteLoop 方法的要求)但调用一个接受任意数量的变量类型参数的方法。
