• 对引用类型的一点理解


         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类型是引用类型,但这种情况不适合字符串类型,因为==已经对字符串进行了重写,用==比较字符串总是比较字符串的内容。

  • 相关阅读:
    PHP操作二进制字节数据
    Linux端口转发-rinted工具部署、配置、使用
    Netty学习(八)-Netty的心跳机制
    Navicat Premium 12破解方法
    App界面设计规范-字体规范
    PHP 扩展开发之Zephir
    rinetd 一个linux下的端口转发工具
    windows node版本管理工具nvm
    vue cli 常见问题汇总
    监听微信返回
  • 原文地址:https://www.cnblogs.com/Komici/p/1344149.html
Copyright © 2020-2023  润新知