ValueType.Equals(null)的底层实现及CLR虚拟机对其结构支持2011-01-06 博客园 lbq1221119在定义任何一个ValueType之后,它都是从System.ValueType继承过来的,默认的就继承了Equals方法和GetHashCode方法,在使用的时候,必须主意的是最好重写自定义ValueType的这两个方法,因为可能带来性能上面的严重问题或者是比较的不正确。譬如定义下面这样的一个结构体值类型:struct TestValueType { public int Myint; public float Myfloat; } TestValueType V1,V2; V1.Equals(V2);可以翻开sscli看看ValueType的equals方法的实现:public override bool Equals (Object obj) { if (null==obj) { return false; } RuntimeType thisType = (RuntimeType)this.GetType(); RuntimeType thatType = (RuntimeType)obj.GetType(); if (thatType!=thisType) { return false; } Object thisObj = (Object)this; Object thisResult, thatResult; // if there are no GC references in this object we can avoid reflection // and do a fast memcmp if (CanCompareBits(this)) return FastEqualsCheck(thisObj, obj); FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (thisResult == null) { if (thatResult != null) return false; } else if (!thisResult.Equals(thatResult)) { return false; } } return true; }首先得到比较两个对象的Type,如果类型不一样就直接返回。然后对于能够进行快速比较的值类型,就使用快速比较:// if there are no GC references in this object we can avoid reflection // and do a fast memcmp if (CanCompareBits(this)) return FastEqualsCheck(thisObj, obj);