gpt4 book ai didi

c# - 是否可以在 C# 中扩展 'using' block ?

转载 作者:IT王子 更新时间:2023-10-29 04:46:00 25 4
gpt4 key购买 nike

有没有办法扩展 using C# 中的 block 以这样一种方式将委托(delegate)作为 IDisposable 对象旁边的第二个参数,并在每次内部抛出异常时执行 using阻止?

假设我们有一个代表,像这样:

public delegate void ExceptionHandler(Exception ex);

假设我有一个匹配该委托(delegate)的方法,如下所示:

public void Log(Exception ex)
{
// Some logging stuff goes here
}

我想完成这样的事情:

using(SqlConnection connection = new SqlConnection(""), Log)
{

}

有没有办法以这种方式扩展 C#?

最佳答案

using block 是 try finally block 的简写,它在 finally 中调用了 Dispose .它不能扩展到不止于此。您想要的是 try catch finally 的功能,所以为什么不完全使用它:

SqlConnection connection = new SqlConnection("");
try {

}
catch (Exception exc) {
Log(exc);
}
finally {
connection.Dispose();
}

这具有 try catch finally 的所有优点,例如捕获多种异常类型和 C# 6.0 异常过滤器。考虑一下:

SqlConnection connection = new SqlConnection("");
try {

}
catch (SqlException exc) when (exc.Number > 0) {
//Handle SQL error
}
catch (Exception exc) {
Log(exc);
}
finally {
connection.Dispose();
}

如果你想重用标准化的 try catch finally block ,你可以使用委托(delegate):

static class ErrorHandler {
public static ExecuteWithErrorHandling<T>(Func<T> createObject,
Action<Exception> exceptionHandler, Action<T> operation) where T : IDisposable {

T disposable = createObject();
try {
operation(disposable);
}
catch (Exception exc) {
exceptionHandler(exc);
}
finally {
disposable.Dispose();
}
}
}

你可以这样调用它:

ErrorHandler.ExecuteWithErrorHandling(() => new SqlConnection(""), Log, connection => {
//Use connection here
});

关于c# - 是否可以在 C# 中扩展 'using' block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42510245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com