1

我目前(过去也曾)使用此循环来查看自定义类数组,并确保数组中每个类的布尔成员值相等。有没有更好的(更有效,可能更简单的编码)方法来做到这一点?

由于这种解释非常糟糕,并且缺乏更好的解释方法,我会简单地问:“有没有更好的方法来优化‘这个’循环?”

//set to true so the loop runs
boolean AllArentEqual = true;

while (AllArentEqual){
    //do some stuff to make stuff equal        



    ///// Check if stuff is equal /////
    //set to false to determine later
    AllArentEqual = false;

    //check if any aren't equal
    for (int i = 1; i < anArrayOfClass.length; i++){
        if (anArrayOfClass[i - 1].BooleanValue != anArrayOfClass[i].BooleanValue){
            //one isn't equal so set the loop to be re-run
            AllArentEqual = true;
        }
    } 


} //loop until stuff is equal
4

3 回答 3

2

一个明显的小改进是添加了一个break

for (int i = 1; i < anArrayOfClass.length; i++){
    if (anArrayOfClass[i - 1].BooleanValue != anArrayOfClass[i].BooleanValue){
        //one isn't equal so set the loop to be re-run
        AllArentEqual = true;
        break;   // We're done in this round
    }
}

一旦确定并非所有人都是平等的,就没有必要进一步检查了。

于 2012-09-20T22:34:34.193 回答
1

我会通过提取一个方法来修改它,然后可能做一些类似的事情:

AttemptMakeEqual(anArrayOfClass);
while (anArrayOfClass.Any(c => c.BooleanValue != anArrayOfClass[0].BooleanValue))
{
    AttemptMakeEqual(anArrayOfClass);
}


// Extract out a method to:
void AttemptMakeEqual(YourClass[] values)
{
    //do some stuff to make stuff equal  
}

如果您有可能拥有“所有相等”的值,并且您并不总是需要先运行该操作即:您的新版本),您可以这样做:

while (anArrayOfClass.Any(c => c.BooleanValue != anArrayOfClass[0].BooleanValue))
{
    //do some stuff to make stuff equal  
}
于 2012-09-20T22:34:19.310 回答
0

我可能会做这样的事情:

class Widget
{
  public Widget( bool truthiness )
  {
    this.Truthiness = truthiness ;
  }
  public bool Truthiness { get ; private set ; }
}

class FooBar
{
  private Widget[] Widgets { get ; private set; }

  private Widget[] GetSomeWidgets()
  {
      throw new NotImplementedException() ;
  }
  public FooBar()
  {
    Widgets = GetSomeWidgets() ;
  }

  private void WorkOnWidgets()
  {
    throw new NotImplementedException() ;
  }

  public void MakeEqual()
  {
    bool areEqual ; // zero or one widget and it's not a problem
    while ( !(areEqual=CheckIfAllWidgetsEqual()) )
    {
      WorkOnWidgets() ;
    }
    return ;
  }

  public bool CheckIfAllWidgetsEqual()
  {
    bool value = true ;
    if ( Widgets.Length > 1 )
    {
      Widget first        = Widgets[0] ;
      Widget firstUnequal = Widgets.Skip(1).FirstOrDefault( x => x.Truthiness != first.Truthiness ) ;
      value = firstUnequal != null ;
    }
    return value ;
  }

}
于 2012-09-21T00:03:10.037 回答