zoukankan      html  css  js  c++  java
  • c#对象私有属性在重载Equals中的使用

      一般情况下对象的比较会涉及到重载Equals方法,这里所说的方法只对同类型对象的比较有效。
      请看下面两段代码:
      1。不同类的比较

    public enum ComplexionType
    {
        yellow,
        white,
        black
    }


    class Chinese
    {
        
    public Chinese(ComplexionType complexionType)
        
    {
            
    this.complexionType = complexionType;
        }


        
    private ComplexionType complexionType;

        
    public override bool Equals(Object obj)
        
    {
            
    if (!((obj is Chinese) || (obj is Japanese)))
            
    {
                
    return false;
            }
                Japanese japanese = (Japanese)obj;
            
    return this.complexionType == japanese.Complexion;
        }

    }


    class Japanese
    {
        
    public Japanese(ComplexionType complexionType)
        
    {
            
    this.complexionType = complexionType;
        }


        
    private ComplexionType complexionType;

        
    public ComplexionType Complexion
        
    {
            
    get
            
    {
                
    return complexionType;
            }

        }

    }

      注意到上面,如果能直接引用到japanese.complexionType就好了,不过它不是public所以访问不到。
      但是,如果,我想对同样的Chinese类型做比较,情况就不同了,修改上面的Equals
    public override bool Equals(Object obj)
    {
        
    if (!(obj is Chinese))
        
    {
            
    return false;
        }

        Chinese chinese 
    = (Chinese)obj;
        
    return this.complexionType == chinese.complexionType;
    }

      虽然,同样定义了Chinese类型的实例,不过这里可以访问到该变量的private部分。
  • 相关阅读:
    PHP——下载图片到本地代码
    PHP接收GET中文参数乱码的原因及解决方案
    防止表单按钮多次提交
    网站页面自动跳转
    php--防止DDos攻击代码
    数据库日期查询存在的问题
    html局部页面打印
    php中::的使用
    php基础:define()定义常数函数
    百度ueditor 拖文件或world 里面复制粘贴图片到编辑中 上传到第三方问题
  • 原文地址:https://www.cnblogs.com/hill/p/98513.html
Copyright © 2011-2022 走看看