個人而言,我會使用二進制搜索尋找下一個組件。 ..
- 開始n = 1的
- 確實TestAssembly1.dll存在嗎? (是)
- TestAssembly2.dll是否存在? (是)
- TestAssembly4.dll是否存在? (是)
- TestAssembly8.dll存在嗎? (是)
- TestAssembly16.dll是否存在? (是)
- TestAssembly32.dll是否存在? (無)
和16和32之間沒有使用二進制搜索:
- 確實TestAssembly24.dll存在嗎? (是)
- TestAssembly28.dll存在嗎? (是)
- TestAssembly30.dll存在嗎? (no)
- TestAssembly29.dll是否存在? (是)
所以使用TestAssembly30.dll
這避免了需要單獨保留計數,所以它甚至會工作,如果你刪除所有文件 - 和二進制搜索意味着你不這樣做表現太差。
未經測試,但如下所示;還注意到,根據文件存在什麼立即是一個競爭條件(儘管通常是非常渺茫的一個):
static string GetNextFilename(string pattern) {
string tmp = string.Format(pattern, 1);
if (tmp == pattern) {
throw new ArgumentException(
"The pattern must include an index place-holder", "pattern");
}
if (!File.Exists(tmp)) return tmp; // short-circuit if no matches
int min = 1, max = 2; // min is inclusive, max is exclusive/untested
while (File.Exists(string.Format(pattern, max))) {
min = max;
max *= 2;
}
while (max != min + 1) {
int pivot = (max + min)/2;
if (File.Exists(string.Format(pattern, pivot))) {
min = pivot;
}
else {
max = pivot;
}
}
return string.Format(pattern, max);
}
這取決於問題域。你需要特別處理差距嗎?在正常情況下,你希望只有少數文件存在於目錄中。(在一個目錄中獲得完整的文件列表要比同樣數量的file.exist操作便宜得多) – 2009-05-26 08:21:20