C#值类型和引用类型与Equals方法


- Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).
(当你要重载引用形式的equal的时候,你要比较的两个值得语义必须是引用类型)
- Most reference types must not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.
(当你重载了一个引用类型的equal方法的时候,一定不要重载相等运算符==;当你重载的是值类型的equal方法时候,必须重载相等运算符。)
- You should not override Equals on a mutable reference type. This is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table.
(※不能把Equal方法重载到一个地址可变的量上(因为重载了equal函数我们必须重载GetHashCode方法),一个实例可变引用的散列值会随着他的生存期会一直改变,这会导致我们无法在散列表中找到这个对象。)
- If you are defining a value type that includes one or more fields whose values are reference types, you should override Equals(Object). The Equals(Object) implementation provided by ValueType performs a byte-by-byte comparison for value types whose fields are all value types, but it uses reflection to perform a field-by-field comparison of value types whose fields include reference types.
(如果你自定义了一个值类型,且这个值类型含有引用类型,那么你必须重载Equal方法,在值类型中,Equal方法对于值类型中的值类型的比较是值与值之间的比较(内存中byte o byte),引用类型比较的是两个对象是否指向同一个内存地址)
- If you override Equals and your development language supports operator overloading, you must overload the equality operator.
(如果你重载了值类型的Equal方法,那么你一定要重载相等运算符)
- You should implement the IEquatable<T> interface. Calling the strongly typed IEquatable<T>.Equals method avoids boxing the obj argument.
(如果你重载了值类型Equal方法,推荐同时实现IEquatable<T> 接口,比较时使用IEquatable<T> 接口而不是把实例封箱到Object中)。(值类型的重载也是要重载GetHashCode的。)
- x.Equals(x) returns true. This is called the reflexive property.(自己等于自己为真)
- x.Equals(y) returns the same value as y.Equals(x). This is called the symmetric property.(可交换性)
- if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true. This is called the transitive property.(可传递性)
- Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.(与引用无关)
- x.Equals(null) returns false. However, null.Equals(null) throws an exception; it does not obey rule number two above.(与null进行比较返回假)
struct结构隐式继承 System.ValueType,这个类已经重写了Object.Equals(Object)方法,但是这个重写过的方法是用的反射技术来检测所有的public和非public属性,尽管这个操作在struct类型里面用是正确的,但是这个操作是很慢的。换句话说,如果我们想自定义自己的值类型,最好是从class继承并改写Equals方法。
string str1 = "Fuck";
string str2 = "Fuck";
- Override the virtualObject.Equals(Object) method. In most cases, your implementation of bool Equals( object obj ) should just call into the type-specific Equals method that is the implementation of the System.IEquatable<T> interface. (See step 2.)
(重写Equals方法或者实现System.IEquatable<T>接口)
- Implement the System.IEquatable<T> interface by providing a type-specific Equals method. This is where the actual equivalence comparison is performed. For example, you might decide to define equality by comparing only one or two fields in your type. Do not throw exceptions from Equals. For classes only: This method should examine only fields that are declared in the class. It should call base.Equals to examine fields that are in the base class. (Do not do this if the type inherits directly from Object, because the Object implementation of Object.Equals(Object) performs a reference equality check.)
(System.IEquatable<T>接口里面可以仅实现部分比较,但绝对不要在Equals里面抛出异常,如果比较的对象有基类,必须调用base.Equals方法)
- Optional but recommended: Overload the == and != operators.
(最好重载==和!=运算符(同时实现))
- Override Object.GetHashCode so that two objects that have value equality produce the same hash code.
(必须重写Object.GetHashCode)
- Optional: To support definitions for "greater than" or "less than," implement the IComparable<T> interface for your type, and also overload the <= and >= operators.
(大于小于号这些可选,比如复数类的时候就需要这些运算符重载)。
class Test1
{
public string Name { get; set; } public Test1(string name)
{
Name = name;
} public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != typeof(Test1))
return false; Test1 testObj = obj as Test1; return this.Name == testObj.Name;
} public static bool operator==(Test1 t1, Test1 t2)
{
return t1.Equals(t2);
} public static bool operator !=(Test1 t1, Test1 t2)
{
return !(t1 == t2);
} public override int GetHashCode()
{
return base.GetHashCode();
}
}
这个时候我们可以把Test1来进行值的比较了,但是上面的代码并没有真正重载GetHashCode,以至于我们会导致下面的问题,我们写入下面的代码:
class Program
{
static void Main(string[] args)
{
Test1 t1 = new Test1("HaHa");
Test1 t2 = new Test1("HaHa"); Console.WriteLine("t1.Equals(t2)? {0}", t1.Equals(t2));
Console.WriteLine("t1 == t2? {0}", t1 == t2); List<Test1> list = new List<Test1>();
list.Add(t1); Console.WriteLine("list contains Test1(HaHa)? {0}", list.Contains(t2));
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
Test1 t1 = new Test1("HaHa");
Test1 t2 = new Test1("HaHa"); Console.WriteLine("t1.Equals(t2)? {0}", t1.Equals(t2));
Console.WriteLine("t1 == t2? {0}", t1 == t2); ICollection<Test1> list = new HashSet<Test1>();
list.Add(t1); Console.WriteLine("list contains Test1(HaHa)? {0}", list.Contains(t2)); Dictionary<Test1, int> dict = new Dictionary<Test1, int>();
dict.Add(t1, ); Console.WriteLine("dict contains Test1(HaHa)? {0}", dict.Keys.Contains(t2));
Console.ReadKey();
}
}
public override int GetHashCode()
{
return Name.GetHashCode();
}

class Test : IEquatable<Test>
{
public Test(string name)
{
Name = name;
} public bool Equals(Test other)
{
return this.Name == other.Name;
} public override bool Equals(object obj)
{
return base.Equals(obj);
} public override int GetHashCode()
{
return Name.GetHashCode();
} public string Name { get; set; }
}
struct Test1
{
public string Name { get; set; } public Test1(string name)
{
Name = name;
} public override bool Equals(object obj)
{
if (obj is Test1)
{
return this.Name == ((Test1)obj).Name;
}
return false;
} public static bool operator==(Test1 t1, Test1 t2)
{
return t1.Equals(t2);
} public static bool operator!=(Test1 t1, Test1 t2)
{
return !(t1.Equals(t2));
} public override int GetHashCode()
{
return Name.GetHashCode();
}
}
C#值类型和引用类型与Equals方法的更多相关文章
- [c#基础]值类型和引用类型的Equals,==的区别
引言 最近一个朋友正在找工作,他说在笔试题中遇到Equals和==有什么区别的题,当时跟他说如果是值类型的,它们没有区别,如果是引用类型的有区别,但string类型除外.为了证实自己的说法,也研究了一 ...
- C#类和接口、虚方法和抽象方法及值类型和引用类型的区别
1.C#类和接口的区别接口是负责功能的定义,项目中通过接口来规范类,操作类以及抽象类的概念!而类是负责功能的具体实现!在类中也有抽象类的定义,抽象类与接口的区别在于:抽象类是一个不完全的类,类里面有抽 ...
- .net学习之.net和C#关系、运行过程、数据类型、类型转换、值类型和引用类型、数组以及方法参数等
1..net 和 C# 的关系.net 是一个平台,C#是种语言,C#语言可以通过.net平台来编写.部署.运行.net应用程序,C#通过.net平台开发.net应用程序2..net平台的重要组成FC ...
- ==和Equals与值类型和引用类型
==和Equals 对于值类型来说判断的是值,对于引用类型来说判断的是堆地址 注意:string 是引用类型(也可看做只读char[]数组)(字符串的不可变性·拘留池)特殊的值类型(使用==.Equa ...
- 从CLR角度来看值类型与引用类型
前言 本文中大部分示例代码来自于<CLR via C# Edition3>,并在此之上加以总结和简化,文中只是重点介绍几个比较有共性的问题,对一些细节不会做过深入的讲解. 前几天一直忙着翻 ...
- 学习记录 java 值类型和引用类型的知识
1. Java中值类型和引用类型的不同? [定义] 引用类型表示你操作的数据是同一个,也就是说当你传一个参数给另一个方法时,你在另一个方法中改变这个变量的值, 那么调用这个方法是传入的变量的值也将改变 ...
- Windows Phone 开发起步之旅之二 C#中的值类型和引用类型
今天和大家分享下本人也说不清楚的一个C#基础知识,我说不清楚,所以我才想把它总结一下,以帮助我自己理解这个知识上的盲点,顺便也和同我一样不是很清楚的人一起学习下. 一说起来C#中的数据类型有哪些,大 ...
- 值类型与引用类型(特殊的string) Typeof和GetType() 静态和非静态使用 参数传递 相关知识
学习大神博客链接: http://www.cnblogs.com/zhili/category/421637.html 一 值类型与引用类型 需要注意的string 是特殊类型的引用类型. 使用方法: ...
- C#基础(六)——值类型与引用类型
CLR支持两种类型:值类型和引用类型. 值类型包括C#的基本类型(用关键字int.char.float等来声明),结构(用struct关键字声明的类型),枚举(用enum关键字声明的类型):而引用类型 ...
随机推荐
- echarts散点图重叠
今天做echarts图标,使用了散点图.很快实现,发现数据不对,应该是3个的企业,页面只显示了2个,查了半天才发现原来是有两个重叠了.想办法解决了,在网上费劲九牛二虎只力终于找到了解决的方法,下面来解 ...
- Mybatis中分页存在的坑1
站在巨人的肩膀上 https://www.cnblogs.com/esileme/p/7565184.html 环境:Spring 4.2.1 Mybatis 3.2.8 pagehelper 5.1 ...
- Java 执行linux命令(转)
转自 http://blog.csdn.net/a19881029/article/details/8063758 java程序中要执行linux命令主要依赖2个类:Process和Runtime 首 ...
- 微信开发(一)URL配置
启用开发模式需要先成为开发者,而且编辑模式和开发模式只能选择一个,进入微信公众平台-开发模式,如下: 需要填写url和token,当时本人填写这个的时候花了好久,我本以为填写个服务器的url就可以了( ...
- JSP && Servlet | 上传图片到数据库
参考博客: https://blog.csdn.net/qiyuexuelang/article/details/8861300 Servlet+Jsp实现图片或文件的上传功能 https://blo ...
- jq解析xml
注意:url路径不能用相对路径,需要加入http协议
- insert后面value可控的盲注(第一次代码审计出漏洞)
这个叫诗龙的cms真的很感谢他的编写人,全站注入~~一些特别白痴的就不说了,这里有一个相对有点意思的 很明显的注入,然后去直接利用报错注入想爆出数据结果发现没有开报错模式. 报错注入http://ww ...
- 在 Java 的多线程中,如何去判断给定的一个类是否是线程安全的(另外:synchronized 同步是否就一定能保证该类是线程安全的。)
同步代码块和同步方法的区别:同步代码块可以传入任意对象,同步方法中 如果多个线程检查的都是一个新的对象,不同的同步锁对不同的线程不具有排他性,不能实现线程同步的效果,这时候线程同步就失效了. 两者的区 ...
- String的小笔记
String类的对象是不可变的! 在使用String类的时候要始终记着这个观念.一旦创建了String对象,它就不会改变. String类中也有可以改变String中字符串的方法,但只要是涉及改变的方 ...
- Springboot的static和templates
static和templates部分参考博客:https://blog.csdn.net/wangb_java/article/details/71775637 热部署参考博客:https://www ...