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

Har*_*rps 7 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();
}
Run Code Online (Sandbox Code Playgroud)

感谢您的输入.

Evk*_*Evk 8

您可以使用扩展方法来"简化"此使用模式:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你像这样使用它:

string myResult = new myDisposableType().GetThenDispose(c => c.GetResult());
Run Code Online (Sandbox Code Playgroud)


Jam*_*iec 5

不,没有这样的捷径.你原来的方式是对的.

如果经常这样做,你可以将它包装在一个函数中

public class Utilities 
{
    public static TReturn GetValueFromUsing<T,TReturn>(Func<T,TReturn> func) where T : IDisposable, new()
    {
        TReturn result = default(TReturn)
        using(var instance = new T())
            result = func(instance);
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

var result = Utilities.GetValueFromUsing<myDisposableType,string>(x => x.GetResult());
Run Code Online (Sandbox Code Playgroud)

但男人会有点矫枉过正.


SO *_*ood 5

这很有趣,因为我几天前开始在C#中阅读函数式编程,其中一个例子是:

public static TResult Using<TDisposable, TResult>(TDisposable disposable, Func<TDisposable, TResult> func) 
    where TDisposable : IDisposable
{
    using (disposable)
    {
        return func(disposable);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

 var result = Using(new DbConnection(), x => x.GetResult());
Run Code Online (Sandbox Code Playgroud)

请注意,与发布的其他答案不同,此函数绝对没有责任,但func无论如何都得到结果TDisposable.