我理解将一个引用类型变量分配给另一个引用类型变量的理论概念,只复制引用,而不是对象。将一个值类型变量分配给另一个值,该对象被复制。但是我无法发现代码中的不同。有人会好好指出以下两个代码块之间的区别吗?谢谢!C#引用类型赋值VS值类型赋值
参考类型分配
using System;
class Employee
{
private string m_name;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
}
class Program
{
static void Main()
{
Employee joe = new Employee();
joe.Name = "Joe";
Employee bob = new Employee();
bob.Name = "Bob";
Console.WriteLine("Original Employee Values:");
Console.WriteLine("joe = " + joe.Name);
Console.WriteLine("bob = " + bob.Name);
// assign joe reference to bob variable
bob = joe;
Console.WriteLine();
Console.WriteLine("Values After Reference Assignment:");
Console.WriteLine("joe = " + joe.Name);
Console.WriteLine("bob = " + bob.Name);
joe.Name = "Bobbi Jo";
Console.WriteLine();
Console.WriteLine("Values After Changing One Instance:");
Console.WriteLine("joe = " + joe.Name);
Console.WriteLine("bob = " + bob.Name);
Console.ReadKey();
}
}
VALUE类型分配
using System;
struct Height
{
private int m_inches;
public int Inches
{
get { return m_inches; }
set { m_inches = value; }
}
}
class Program
{
static void Main()
{
Height joe = new Height();
joe.Inches = 71;
Height bob = new Height();
bob.Inches = 59;
Console.WriteLine("Original Height
Values:");
Console.WriteLine("joe = " + joe.Inches);
Console.WriteLine("bob = " + bob.Inches);
// assign joe reference to bob variable
bob = joe;
Console.WriteLine();
Console.WriteLine("Values After Value Assignment:");
Console.WriteLine("joe = " + joe.Inches);
Console.WriteLine("bob = " + bob.Inches);
joe.Inches = 65;
Console.WriteLine();
Console.WriteLine("Values After Changing One Instance:");
Console.WriteLine("joe = " + joe.Inches);
Console.WriteLine("bob = " + bob.Inches);
Console.ReadKey();
}
}
输出是理所应当的。那么,问题是什么? – shahkalpesh 2009-08-02 19:54:40
按照这个例子,它只是第三点,它是不同的。更改其中一个引用会影响引用它的其他实例。值类型不是这种情况。 – shahkalpesh 2009-08-02 19:56:46