我檢查喬恩斯基特的MoreLinq,我開始好奇的獲取擴展的源代碼MoreLinq收購。它有什麼作用?
/// <summary>
/// Ensures that a source sequence of <see cref="IDisposable"/>
/// objects are all acquired successfully. If the acquisition of any
/// one <see cref="IDisposable"/> fails then those successfully
/// acquired till that point are disposed.
/// </summary>
/// <typeparam name="TSource">Type of elements in <paramref name="source"/> sequence.</typeparam>
/// <param name="source">Source sequence of <see cref="IDisposable"/> objects.</param>
/// <returns>
/// Returns an array of all the acquired <see cref="IDisposable"/>
/// object and in source order.
/// </returns>
/// <remarks>
/// This operator executes immediately.
/// </remarks>
public static TSource[] Acquire<TSource>(this IEnumerable<TSource> source)
where TSource : IDisposable
{
if (source == null) throw new ArgumentNullException("source");
var disposables = new List<TSource>();
try
{
disposables.AddRange(source);
return disposables.ToArray();
}
catch
{
foreach (var disposable in disposables)
disposable.Dispose();
throw;
}
}
從我的理解它接收到IEnumerable<IDisposable>
並創建一個List<IDisposable>
。
我無法理解這裏可能出現的問題。
任何人都可以解釋給我,並可能提供一個例子,這個擴展可以是有用的嗎?
我認爲Jon Skeet是最適合回答這個問題的原因很明顯。就示例而言,我們只是說我有一個關閉文件描述符的序列/數組/列表,我想打開它們並對它們做一些事情(我需要所有這些描述符)。如果有任何文件無法打開,我想自動關閉所有其他描述符。在這種情況下,「Acquire」就可以做到這一點。 –
懶惰的枚舉可能會在迭代過程中拋出一個異常。在這種情況下,你應該「處理」所有早期的對象,這個函數就是這樣做的。 – CodesInChaos
所有的答案都是完美的,我想將它們全部標記爲*接受*,但我只能選擇一個。看着答案讓我感覺像是「哦」 –