我想知道是否有可能在finally块中获取函数的返回值.
我有一些像这样的代码.
try
{
return 1;
}
finally
{
//Get the value 1
}
Run Code Online (Sandbox Code Playgroud)
我知道可以添加一个可以保存返回值的变量.但我想知道是否有可能以任何方式获得价值.
谢谢
int value = -1;
try
{
value = 1;
}
finally
{
// Now the value is available
}
return value;
Run Code Online (Sandbox Code Playgroud)
如果你想使用变量方法并提前返回,你可以这样做:
int Method()
{
int @return = -1;
try
{
@return = -2;
return @return;
}
finally
{
// do something with @return
}
}
Run Code Online (Sandbox Code Playgroud)
正如其他人已经提到的那样,在这种情况下你必须使用变量.但是,您可以使用C#3.0 lambda函数将此行为模式包装为可重用的方法:
static T TryFinally<T>(Func<T> body, Action<T> finallyHandler) {
T result = default(T);
try {
result = body();
} finally {
finallyHandler(result);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
该TryFinally方法允许您在不重复模式的情况下编写最初需要的内容:
TryFinally(() => {
// body of the method
return 1;
}, result => {
// do whatever you need with 'result' here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4557 次 |
| 最近记录: |