如何防止递归 [英] How to prevent recursion

查看:36
本文介绍了如何防止递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定名为 OrderInfo 的类,确保其他开发人员(包括我自己)不会意外地出现此处所示的递归错误的最佳方法是什么:

Given the class named OrderInfo, what's the best way to ensure other developers (including myself) do not accidentally make the recursive error shown here:

public class OrderInfo : ICollection<UnitModule> {

  // Other code for class...

  public bool Changed { get; private set; }

  public void Save() {
    Save(this); // I want the static method to handle saving the data
  }

  public static void Save(OrderInfo item) {
    for (int i = 0; i < item.Count; i++) {
      if (item[i].Changed) {
        item[i].Save();
      }
    }
    if (item.Changed) {
      item.Save(); // this would be bad!
      // Instead, all of the other developers should have to call the
      // Database Save method.
      // Is there a way to ensure this happens or do I have to rely on
      // everyone remembering this?
    }
  }

}

使用标记的答案,我可以按如下方式编写我的类(为什么无关紧要 - 这只是防止递归):

Using the marked answer, I can write my class as follows (why does not matter - this simply prevents the recursion):

public class OrderInfo : ICollection<UnitModule> {
  // Other code for class...
  bool saving; // <= new variable
  public bool Changed { get; private set; }

  public void Save() {
    if (!saving) {
      Save(this);
    } else {
      throw new Exception("This item is already being saved.");
    }
  }

  public static void Save(OrderInfo item) {
    item.saving = true;
    try {
      for (int i = 0; i < item.Count; i++) {
        if (item[i].Changed) {
          item[i].Save();
        }
      }
      if (item.Changed) {
        // item.Save(); <= NOTE: this would throw an exception
        DataAccess.Save(item);
        item.Changed = false;
      }
    } finally {
      item.saving = false;
    }
  }
}

推荐答案

这可能有效:

public static void Save(OrderInfo item) {
  for (int i = 0; i < item.Count; i++) {
    if (item[i].Changed) {
      item[i].Save();
    }
  }
  if (item.Changed) {
    item.Changed = false; // prevents recursion!
    item.Save();
    if error saving then item.Changed = true; // reset if there's an error
  }
}

这篇关于如何防止递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆