【发布时间】:2011-05-18 21:55:44
【问题描述】:
鉴于名为OrderInfo 的类,确保其他开发人员(包括我自己)不会意外地出现此处所示的递归错误的最佳方法是:
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?
}
}
}
编辑:使用标记的答案,我可以如下编写我的课程(为什么不重要 - 这只是防止递归):
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;
}
}
}
【问题讨论】:
-
你有什么特别的理由让它成为静态成员?
-
指向answers here会是陈词滥调吗?
-
@Marc Gravell - 即将发表完全相同的评论!
-
发生了什么?我的问题发了两次吗?这在我之前发生过几次。是我的鼠标手指太抽搐还是谷歌浏览器出现故障?