大家都知道,引用类型在参数传递中,在被调用函数中的更改将反映到调用函数中,但是它是否可以在被调用函数中重新实例化呢?例如:
public class test
{
int count;
public int Count
{
get { return count; }
set { count = value; }
}
}
class Program
{
static void Main(string[] args)
{
test t = new test();
t.Count = 20;
TestObject(t);
Console.WriteLine(t.Count);
Console.ReadKey();
}
private static void TestObject(test t)
{
t = new test();
t.Count = 50;
}
}
这个时候t.Count的值是多少呢?你也许说是50或20;但是答案是20,假如将private static void TestObject(test t)函数中的
t = new test();注释掉或删除,结果又是什么呢?答案是50 ,这一切都是为什么?
因为引用对象传递时,可以改变对象的成员值,但不可以替换原来的对象引用(地址),替换后虽然不会编译错误,仍然可以正常运行,但是不是我们想要的结果。也就是说我们不能去试图构造新的对象来改变原来的对象