访问finally块中函数返回的值

时间:2010-03-01 21:30:42

标签: c# .net

我想知道是否可以在finally块中获取函数的返回值。

我有一些像这样的代码。

try
{
    return 1;
}
finally
{
    //Get the value 1
}

我知道可以添加一个可以保存返回值的变量。但我想知道是否有可能以任何方式获得价值。

由于

6 个答案:

答案 0 :(得分:27)

不,你不能这样做。

答案 1 :(得分:9)

int value = -1;

try 
{ 
    value = 1; 
} 
finally 
{ 

    // Now the value is available
} 

return value;

答案 2 :(得分:9)

如果你想使用变量方法并提前返回,你可以这样做:

int Method()
{
    int @return = -1;
    try
    {
        @return = -2;
        return @return;
    }
    finally
    {
        // do something with @return
    }
}

答案 3 :(得分:8)

正如其他人已经提到的那样,在这种情况下你必须使用一个变量。但是,您可以使用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;
}

TryFinally方法允许您在不重复模式的情况下编写最初需要的内容:

TryFinally(() => { 
    // body of the method
    return 1; 
  }, result => {
    // do whatever you need with 'result' here
  });

答案 4 :(得分:4)

VB.Net允许您这样做:

Public Function GetValue() As Integer
    Try
        GetValue = 2
    Catch
        'Something happens
    Finally
        'Do something with GetValue
    End Try
End Function

它告诉你一些关于JIT编译器将要做什么。

答案 5 :(得分:0)

我认为实际的问题是 - 我可以系统地跟踪各种功能的退出(和输入吗?) - 可能是跟踪/故障排除等等。如果是aspect.net。这使您可以动态地将代码插入到事物中