避免为不同的代码执行重复for循环
本文关键字:执行 for 循环 代码 | 更新日期: 2023-09-27 18:06:57
我有一个条件假设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
}
}
}
}
}
为了在大循环的情况下优化性能我把switch-case
放在for循环之外所以代码变成这样:
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次(或作为案例的数量),这违反了软件设计的一次且仅一次原则。
我试图传递一个委托,但我应该调用的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;
}
这将允许您将循环合并到一个方法中,同时改变实际执行的内容。当你说:
…但是我应该调用的3个函数有不同的参数…
你的意思。我假设有两种情况:
- 你打算调用的三个方法有不同的值作为参数传递。
或
- 你打算调用的三个方法有不同的数量传递给它们的参数。
无论哪种方式,您都可以通过构建前面的解决方案来解决这个问题。像这样:
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
方法的要求),但调用一个接受任意数量的变量类型参数的方法。
我试图传递一个委托,但我应该调用的3个函数有不同的论点,有人能告诉我一个简洁的解决方案吗案例?
创建3个不带参数的函数,调用现有函数。例如…
Func HandleDog = ()=>{function1(param1, param2);};
Func HandleCat = ()=>{function2(param1);};
对于Robert和William提供的答案,我个人认为下面这个更简洁:
Action animalMethod;
switch (animalType)
{
case Dog:
animalMethod = new Action(() => CallMethod1(animal as Dog));
break;
case Cat:
animalMethod = new Action(() => CallMethod1(animal as Dog));
break;
case Elephant:
animalMethod = new Action(() => CallMethod1(animal as Dog));
break;
default:
throw new Exception("Unknown Animal");
}
for (var i = 0; i < 100; i++)
{
if (some conditions on i)
{
for (var j = 0; j < 100; j++)
{
if (some condition on j)
{
animalMethod();
}
}
}
}