C# using 带有返回值的语句或内联声明的结果变量

标签 c# using

我想知道是否有一些方法可以优化 using 语句来一起声明和分配它的输出(当它是单个值时)。

例如,类似于内联声明 out 参数的结果变量的新方法。

//What I am currently doing:
string myResult;
using(var disposableInstance = new myDisposableType()){
    myResult = disposableInstance.GetResult();
}

//That would be ideal
var myResult = using(var disposableInstance = new myDisposableType()){
    return disposableInstance.GetResult();
}

//That would be great too
using(var disposableInstance = new myDisposableType(), out var myResult){
    myResult = disposableInstance.GetResult();
}

感谢您的输入。

最佳答案

您可以使用扩展方法来“简化”这种使用模式:

public static class Extensions {
    public static TResult GetThenDispose<TDisposable, TResult>(
        this TDisposable d, 
        Func<TDisposable, TResult> func) 
            where TDisposable : IDisposable {

        using (d) {
            return func(d);
        }
    }
}

然后你像这样使用它:

string myResult = new myDisposableType().GetThenDispose(c => c.GetResult());

关于C# using 带有返回值的语句或内联声明的结果变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068490/

相关文章:

c# - DinkToPdf Net Core 无法加载 DLL 文件

c# - 数据库形状列表

c# - C/C# 中更快的模数?

c# - 异常处理(矛盾的文档/尝试最终与使用)

c# - 为什么要删除不必要的 C# using 指令?

c++ - 引用依赖类型名

c# - 是否可以在其get和set中获取属性名称的字符串?

c# - 如何在wpf中获取文本框的绑定(bind)

c++ - 如何在 C++11 中处理弱枚举的 `using`?

c++ - 使用关键字公开 protected 重载方法