老实说,我认为在您的情况下,最具可读性和可维护性的只是将这些 if 块中的逻辑移动到函数中:
if(hit.collider.gameObject.tag == "Colour1" && start_time > look_at_time)
{
DoTheThing(new_colour1);
}
if(hit.collider.gameObject.tag == "Colour2" && start_time > look_at_time)
{
DoTheThing(new_colour2);
}
//and so on
void DoTheThing(MyType newColour)
{
newColour.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color);
var colums = GameObject.FindGameObjectsWithTag("column");
foreach( GameObject c in colums)
c.GetComponent<MeshRenderer>().materials[1].color = newColour.orignalMaterial;
}
至于使用switch
你当然可以做这样的事情:
switch(hit.collider.gameObject.tag)
{
case "Colour1":
if (start_time>look_at_time)
{
//do something
}
else if (start_time<look_at_time)
{
//something else
}
else
{
//they are equal, etc, etc
}
break;
case "Colour2":
//and so on
}
或者如果所有 if 块在 和 之间进行相同的比较start_time
,look_at_time
那么您可以将其反转:
enum TimeDifference
{
LessThan,Equal,GreaterThan
}
//just one way to get a constant switchable value, not necessarily the best
var diff = TimeDifference.Equal;
if (start_time>look_at_time) {diff=TimeDifference.LessThan}
else if (start_time<look_at_time) {diff=TimeDifference.GreaterThan}
switch(diff)
{
case TimeDifference.LessThan:
switch(hit.collider.gameObject.tag)
{
case "Colour1":
//do something for Colour1
break;
case "Colour2":
//do something for Colour2
break;
}//end switch Colour
break;
case TimeDifference.GreaterThan
switch(hit.collider.gameObject.tag)
{
case "Colour1":
//do something for Colour1
break;
case "Colour2":
//do something for Colour2
break;
}//end switch Colour
break;
default:
//nested switch for Colour in the == case, you get the idea.
}
尽管上述任何一个与几个格式良好且单独的if
块的可读性是非常值得商榷的。
另一种方法是使用Dictionary<string,Action<int,int>>
: (假设start_time
和look_at_time
都是int
s 并且您的所有逻辑都以某种方式涉及它们)
var Actions = new Dictionary<string,Action<int,int>>();
Actions.Add("Colour1",(s,l)=>{
if (start_time>look_at_time)
{
//do something
}
else if (start_time<look_at_time)
{
//something else
}
else
{
//they are equal, etc, etc
}
});
然后你的主要代码变成 1 行:
Actions[hit.collider.gameObject.tag](start_time,look_at_time);
而且我确信还有更多方法可以重新排列该代码。