开发者

Access the value returned by a function in a finally block

I'd like to know if it is possible to get the return value of a function inside a finally block.

I have some code that is like this.

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

I know it's possible by adding a variable that can hold the returned valu开发者_运维知识库e. But I was wondering if it was possible to get the value in any way.

Thanks


No, you can't do that.


int value = -1;

try 
{ 
    value = 1; 
} 
finally 
{ 

    // Now the value is available
} 

return value;


If you want to use the variable approach and return early, you could do something like this:

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


As others already mentioned, you have to use a variable in this case. However, you can wrap this behavioral pattern into a reusable method using C# 3.0 lambda functions:

static T TryFinally<T>(Func<T> body, Action<T> finallyHandler) { 
  T result = default(T);
  try {
    result = body();
  } finally {
    finallyHandler(result);
  }
  return result;
}

The TryFinally method allows you to write what you originally needed without repeating the pattern:

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


VB.Net allows you to do this:

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

Which tells you a little bit about what the JIT compiler is going to do.


I think the actual question is - can I systematically trace the exit (and entry?) of various functions - presumably for tracing / troubleshooting etc. How about aspect.net. This lets you insert code dynamically into things

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜