是否合法且可以访问finally块中的返回值?

时间:2008-11-20 10:14:21

标签: c# .net vb.net try-catch seh

我希望在离开函数之前设置一个usererror字符串,具体取决于函数中的返回码和变量。

我目前有:

Dim RetVal as RetType

try
...
if ... then
    RetVal = RetType.FailedParse
    end try
endif
...

finally
    select case RetVal
        case ...
            UserStr = ...
    end select
end try

return RetVal

是否可以使用return RetType.FailedParse,然后在finally块中访问它?

3 个答案:

答案 0 :(得分:4)

在C#中执行此操作的唯一真正方法是在方法的开头声明一个变量以保存该值 - 即

SomeType result = default(SomeType); // for "definite assignment"
try {
   // ...
   return result;
}
finally {
    // inspect "result"
}

在VB中,你可能能够直接访问结果 - 因为IIRC它的工作方式与上面的方法类似(方法名称为“结果”)。警告:我真的不是VB人......

答案 1 :(得分:1)

从try块中声明变量,并检查finally块是否已设置。

答案 2 :(得分:1)

我想知道在VB中是否可以(合法地)做到:

Public Function MyFunc() as integer
    Try
      if DoSomething() = FAIL Then
        return FAIL
      end if

  Finally
      if MyFunc = FAIL then
          Me.ErrorMsg = "failed"
      endif
  End Try
End Function

我知道设置MyFunc = FAIL是合法的(作为VB的挂起),它是只写还是可读?我担心这是编码不好的

if MyFunc = FAIL Then

太相似了
if MyFunc() = FAIL Then

有着截然不同的后果!