我们先来看看面试题
static int Test()
{
int x = 1;
try
{
++x;
return x;
}
catch
{
return --x;
}
finally
{
++x;
}
}
static int? Test5()
{
int? x = 1;
try
{
++x;
return x;
}
catch
{
return --x;
}
finally
{
++x;
}
}
static string Test2()
{
string x = "a";
try
{
x+="b";
return x;
}
catch
{
return x += "b";
}
finally
{
x += "c";
}
}
static int[] Test3()
{
int[] x = { 2, 3, 4 };
try
{
x[0] = 99;
return x;
}
catch
{
x[0] = 88;
return x;
}
finally
{
x[0] = 77;
}
}
static Class1 Test4()
{
Class1 class1 = new Class1()
{
a = 3,
b = "a"
};
try
{
class1.a= 2;
class1.b = "b";
return class1;
}
catch
{
class1.a = 22;
class1.b = "bb";
return class1;
}
finally
{
class1.a = 62;
class1.b = "b7";
}
}
其中Class1类如下:
internal class Class1
{
public int a;
public string b;
public object c;
public Class1()
{
}
//public Class1(int a)
//{
// this.a = a;
//}
public Class1(int a,string b,object c)
{
this.a=a;
this.b=b;
this.c=c;
}
public void Print()
{
Console.WriteLine("1"+this.a);
}
public override string ToString()
{
return $"a={a},b={b}";
}
}
然后分别打印它们结果是:
Console.WriteLine($"Test={Test()}");
Console.WriteLine($"Test2={Test2()}");
Console.WriteLine($"Test3={string.Join(',', Test3())}");
Console.WriteLine($"Test4={string.Join(',', Test4().ToString())}");
Console.WriteLine($"Test5={Test5()}");
除去字符串、基本数值类型加上?这种引用类型外(int?也是一种引用类型),其它引用类型的值都在finally处被修改了,因为,return处暂存的是引用类型的地址,在finally处修改的是值而不是地址;字符串、基本数值类型加上?这种引用类型是重新创建新的地址了。数值类型直接修改的是本身的值,在return处会被暂存,finally处修改不对return处会被暂存的值造成修改。