給定一個名爲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;
}
}
}
你有什麼特別的理由讓它成爲一個靜態成員? – Skizz 2011-05-18 21:58:05
指向這裏的[答案](http://stackoverflow.com/questions/6051501/how-to-prevent-recursion)會是陳詞濫調嗎? – 2011-05-18 22:05:10
@Marc Gravell - 即將發佈完全相同的評論! – 2011-05-18 22:07:01