C#是否可以将using语法复制用于其他目的



我可以使用Func<>来复制它,如下所示:

public SimilarSyntax<T>(Func<T> f) 
{
Begin(); 
var result = f(); 
End(); 
return result;
}

然而,这并不完全相同,因为f不能分配调用者已知的变量。


我希望能够复制using语法来清理一些代码
实际代码

void SomeProcedure(object param)
{
Class1 get1;
Class2 get2;
...
ClassN getN;
try
{
_context.SetReadUnCommitted();
get1 _context.Get1(param);
...
get2 _context.Get2(param);
}
finally
{
_context.PutBackOriginalIsolationLevel();
}
_context.Get3(param);
}

我尝试使用的(或其他语法,如using(

void SomeProcedure(object param)
{
Class1 get1;
Class2 get2;
...
ClassN getN;
_context.ExecuteInReadUnCommitted
(
() =>
{
get1 = _context.Get1(param);
get2 = _context.Get2(param);
}
);
_context.Get3(param);
}
public class Context
{
public void ExecuteInReadUnCommitted(Action action)
{
try
{
this.SetReadUnCommitted();
action();
}
finally
{
this.PutBackOriginalIsolationLevel();
}
}
} 

正如其他人所评论的,您可以使用usingIDisposable来实现这一点:

public class Context
{   
public IDisposable ReadUnCommitted()
{
SetReadUnCommitted();
return Disposable.Create(PutBackOriginalIsolationLevel);
}
}

并且,您可以使用它,如下所示:

using (context.ReadUnCommitted())
{
get1 = _context.Get1(param);
// throw new NotImplementedException();
get2 = _context.Get2(param);
}
get3 = _context.Get3(param);

Disposable方法将始终被调用,因为它本质上是像try-finally一样实现的。您可以取消对throw的注释并验证自己。

注:Disposable.Create可以通过using System.Reactive找到。或者,您可以实现自己的:

public static class DisposableEx
{
public static IDisposable Create(Action dispose)
{
return new DisposableImpl(dispose);
}
private class DisposableImpl : IDisposable
{
private readonly Action dispose;
public DisposableImpl(Action dispose)
{
this.dispose = dispose;
}
public void Dispose() => dispose?.Invoke();
}
}

最新更新