除了 Marc Gravell 和 Jon Skeet 给出的答案之外,重要的是要注意对象和其他引用类型在返回时的行为相似,但确实存在一些差异。
返回的“What”遵循与简单类型相同的逻辑:
class Test {
public static Exception AnException() {
Exception ex = new Exception("Me");
try {
return ex;
} finally {
// Reference unchanged, Local variable changed
ex = new Exception("Not Me");
}
}
}
在finally块中为局部变量分配一个新引用之前,返回的引用已经被评估。
执行本质上是:
class Test {
public static Exception AnException() {
Exception ex = new Exception("Me");
Exception CS$1$0000 = null;
try {
CS$1$0000 = ex;
} finally {
// Reference unchanged, Local variable changed
ex = new Exception("Not Me");
}
return CS$1$0000;
}
}
不同之处在于,仍然可以使用对象的属性/方法修改可变类型,如果不小心,可能会导致意外行为。
class Test2 {
public static System.IO.MemoryStream BadStream(byte[] buffer) {
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
try {
return ms;
} finally {
// Reference unchanged, Referenced Object changed
ms.Dispose();
}
}
}
关于 try-return-finally 要考虑的第二件事是“通过引用”传递的参数在返回后仍然可以修改。只有返回值被评估并存储在一个等待返回的临时变量中,任何其他变量仍然以正常方式修改。 out 参数的约定甚至可以在 finally 阻塞之前无法实现。
class ByRefTests {
public static int One(out int i) {
try {
i = 1;
return i;
} finally {
// Return value unchanged, Store new value referenced variable
i = 1000;
}
}
public static int Two(ref int i) {
try {
i = 2;
return i;
} finally {
// Return value unchanged, Store new value referenced variable
i = 2000;
}
}
public static int Three(out int i) {
try {
return 3;
} finally {
// This is not a compile error!
// Return value unchanged, Store new value referenced variable
i = 3000;
}
}
}
像任何其他流结构一样,“try-return-finally”有它的位置,并且可以让代码看起来更简洁,而不是编写它实际编译成的结构。但必须小心使用,以免出现问题。