عبارت using و نحوه استفاده صحیح از آن
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۶/۱۲ ۱۳:۳۱
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
namespace TestUsing
{
public class MyResource : IDisposable
{
public void DoWork()
{
throw new ArgumentException("A");
}
public void Dispose()
{
throw new ArgumentException("B");
}
}
public static class TestClass
{
public static void Test()
{
using (MyResource r = new MyResource())
{
throw new ArgumentException("C");
r.DoWork();
}
}
}
}
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
using (var pdfDoc = new Document(PageSize.A4))
{
//todo: ...
}
using System;
namespace Guard
{
public static class SafeUsing
{
public static void SafeUsingBlock<TDisposable>(this TDisposable disposable, Action<TDisposable> action)
where TDisposable : IDisposable
{
disposable.SafeUsingBlock(action, d => d);
}
internal static void SafeUsingBlock<TDisposable, T>(this TDisposable disposable, Action<T> action, Func<TDisposable, T> unwrapper)
where TDisposable : IDisposable
{
try
{
action(unwrapper(disposable));
}
catch (Exception actionException)
{
try
{
disposable.Dispose();
}
catch (Exception disposeException)
{
throw new AggregateException(actionException, disposeException);
}
throw;
}
disposable.Dispose();
}
}
}
new Document(PageSize.A4).SafeUsingBlock(pdfDoc =>
{
//todo: ...
});
Public Class MyResource
Implements IDisposable
Public Sub DoWork()
Throw New ArgumentException("A")
End Sub
Public Overloads Sub Dispose() Implements System.IDisposable.Dispose
Throw New ArgumentException("B")
End Sub
End Class
Public NotInheritable Class TestClass
Private Sub New()
End Sub
Public Shared Sub Test()
Using r As New MyResource()
Throw New ArgumentException("C")
r.DoWork()
End Using
End Sub
End Class
Module Module1
Sub Main()
Try
TestClass.Test()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module