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关键字声明的类型):而引用类型 ...
随机推荐
- Unity2d 骨骼动画1:介绍
http://bbs.9ria.com/thread-401613-1-1.html by Orlando Pereira and PedroPereira3 days ago2 Comments 在 ...
- JVM加载类的原理机制
在Java中,类装载器把一个类装入Java虚拟机中,要经过三个步骤来完成:装载.链接和初始化,其中链接又可以分成校验.准备.解析装载:查找和导入类或接口的二进制数据: 链接:执行下面的校验.准备和解析 ...
- js实现打印正三角
代码: <html> <head> <title>function</title> </head> <body> <scr ...
- Codeforces 1137D(技巧)
一开始写的第一步让0和1一起走然后第二步再让0走会挂最后一个点--然后探索一下觉得主要问题在于我模拟的一步一步地走.如果这样的话9 2这个数据会使第17步他俩就碰在final点了,而实际上我们想要的效 ...
- JetSpeed2因dom4j包冲突导致PSML页面文件数据丢失
使用JetSpeed2进行二次开发时突然出现在保存Portlet配置信息时出现PSML页面文件数据丢失的情况,几经测试,最终发现是因为Portlet中的dom4j.jar与jetspeed应用中的do ...
- 2个rman自动恢复的脚本
### scripts 1--the scirpt is used for restore db from vcs to a point to time recovery--and the targe ...
- L. Right Build bfs
http://codeforces.com/gym/101149/problem/L 给出一个有向图,从0开始,<u, v>表示要学会v,必须掌握u,现在要学会a和b,最小需要经过多少个点 ...
- Linux--NiaoGe-Service-07网络安全与主机基本防护
Linux系统内自带的防火墙有两层: 第一层:数据包过滤防火墙:IP Filtering和Net Filter 要进入Linux本机的数据包都会先通过Linux预先内置的防火墙(Net Filter) ...
- C#私有的构造函数的作用
C#私有的构造函数的作用:当类的构造函数是私有的时候,也已防止C1 c1=new C1();实例化类.常见的应用是工具类和单例模式. using System;using System.Collect ...
- Asp.net开发必备51种代码
1.//弹出对话框.点击转向指定页面 Response.Write("<script>window.alert('该会员没有提交申请,请重新提交!')</script> ...