代码改变世界

对引用类型的一点理解

2008-11-30 10:39  Komici  阅读(265)  评论(0编辑  收藏  举报

     C#把所有的类都看做是引用类型,那我们比较两个类型的实例是怎么去比较的呢?

     通常我们比较两个引用类型是看这两个引用是否指向内存中相同的地址不是比较引用类型存储数据的内容,指向相同的地址也就是看它是不是引用相同的内存。

     Example:

     public Class Employee

     { 

          public string name;

          public string Name

          {

                    get

                    {

                         return name;

                    }

                    set

                    {

                         name = value;

                    }

          }

 

          public int age;

          public int Age

          {

               get

               {

                     return age;

               }

               set

               {

                     age = value;

               }

          }

 

          public int salary;

          public int Salary

          {

               get

               {

                    return salary;

               }

               set

               {

                    salary = value;

               }

          }

          

     }

 

     --创建类的实例

     Employee emp1;

     Employee emp2 = new Employee2();

     Employee emp3 = new Employee3();

     

     --比较emp1与emp2

     public bool IsEque()

     {

          Employee emp1;

          Employee emp2 = new Employee();

          --emp2指向内存中相同的地址赋给emp1

          emp1  = emp2;

          if(emp1 == emp2)

          {

               reuturn true;

          }

          return false;

     }

     --结果:true

 

     public bool IsEque2()

     {

          Employee emp2 = new Employee();

          emp2.Name = '张三';

          emp2.Age = 30;

          emp2.Salary = 4500;

 

          Employee emp3 = new Employee();

          emp3.Name = '李四';

          emp3.Age = 32;

          emp3.Salary = 5500;

 

          if(emp2 == emp3)

          {

               return true;

          }

          return false;

     }

 

     --结果:false;

     

     说明: 如果类的实例引用相同的内存地址,类的实例相等,反之类的实例引用的内存地址不同,则类的实例不相等。

     

     注意:虽然string类型是引用类型,但这种情况不适合字符串类型,因为==已经对字符串进行了重写,用==比较字符串总是比较字符串的内容。