码迷,mamicode.com
首页 > Windows程序 > 详细

C#之相等性判断探秘

时间:2015-07-19 23:10:23      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

  C#实现相等性判断的方法:

  1. public virtual bool Equals(object obj);
  2. public static bool Equals(object objA, object objB);
  3. public static bool ReferenceEquals(object objA, object objB);
  4. “==”运算符
//确定指定的 System.Object 是否等于当前的 System.Object
public virtual bool Equals(object obj) { return RuntimeHelpers.Equals(this, obj); } //确定是否将指定的 System.Object 实例视为相等 public static bool Equals(object objA, object objB) { return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB))); } //确定指定的 System.Object 实例是否是相同的实例 public static bool ReferenceEquals(object objA, object objB) { return (objA == objB); }

== 和 !=运算符比较内容

   **********************************************************************************************************************

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ValueTypeDemo
{
    //鞋子类
    class Shoes
    {
        private string name; //品名
        private int price;  //单价

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public int Price
        {
            get { return price; }
            set { price = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Shoes S1 = new Shoes();
            Shoes S2 = new Shoes();
            Shoes S3 = S2;

            int x = 5;
            int y = 8;
            int z = x;

            object A = 11;
            object B = A;
            object C = 11;
            //内容比较
            Console.WriteLine(x==y);  //false
            Console.WriteLine(x==z);  //true
            //装箱后按引用比较
            Console.WriteLine(A==B);  //true
            Console.WriteLine(A==C);  //false
            //装箱后按装箱前类型比较值是否相等
            Console.WriteLine(A.Equals(B));  //true
            Console.WriteLine(A.Equals(C));  //true

            Console.WriteLine(Equals(A, B));  //true
            Console.WriteLine(Equals(A, C));  //true
            //强制按引用比较
            Console.WriteLine(ReferenceEquals(A,B));  //true
            Console.WriteLine(ReferenceEquals(A,C));  //false

            Console.ReadKey();
        }
    }
}

 

C#之相等性判断探秘

标签:

原文地址:http://www.cnblogs.com/handsome1008/p/4659393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!