【问题标题】:Is this an efficient use of delegates in C#?这是在 C# 中有效使用委托吗?
【发布时间】:2019-11-13 17:13:42
【问题描述】:

我有一个 while 循环需要调用两种方法之一;调用哪个方法取决于被迭代对象的属性。我没有在此属性上执行 if / switch 语句,而是使用委托在 while 循环外执行 switch 语句。

这用代码更容易解​​释。

public void Plan()
{
   foreach (var itemHeader in estimate.ItemHeaders)
   {
      var scheduleMethod = new Schedule(ScheduleWall);

      switch (itemHeader.Type)
      {
         case TypeEnum.Stair: { scheduleMethod = new Schedule(ScheduleWall); break; }
         case TypeEnum.Wall: { scheduleMethod = new Schedule(ScheduleStair); break; }
      }

      foreach (var item in itemHeader.EstimateItems)
      {
         // this loop will run many, many times
         scheduleMethod(item);
      }
   }
}

private delegate void Schedule(EstimateItem item);

private void ScheduleWall(EstimateItem item)
{
   // do stuff..
}

private void ScheduleStair(EstimateItem item)
{
   // do stuff..
}

在循环内通过itemHeader.EstimateItems 调用委托的替代方法是在该循环内执行switch 语句。它只比较两个枚举,但由于该循环将运行多次,因此在循环之前进行一次比较似乎更有效。

我是否引入了不必要的复杂性?这是使用代表的不好的做法吗?

【问题讨论】:

  • 我认为codereview.stackexchange.com这个问题会更好。
  • @EricWu Code Review 不接受假设/存根代码。在提出此类建议之前,请先熟悉 CR on-topic 页面。
  • 抱歉@Sam,我认为这不是假设的。

标签: c# .net delegates


【解决方案1】:

在这种情况下最有效的方法是没有委托:

public void Plan()
{
   foreach (var itemHeader in estimate.ItemHeaders)
   {
      if(itemHeader.Type == TypeEnum.Wall)
         foreach (var item in itemHeader.EstimateItems)
            ScheduleStair(item);
      else
         foreach (var item in itemHeader.EstimateItems)            
            ScheduleWall(item);
   }
}

这样你就直接调用了方法,甚至可以内联。

【讨论】:

  • 感谢您的回复。对于这个问题,我被否决了,所以我认为这表明这不是很好地使用代表..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 1970-01-01
相关资源
最近更新 更多