我在 .NET Reflector 中四处寻找,并注意到对于像“String”这样的引用类型,“==”运算符有一个显式重载:
typeof(string).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public)
返回:“==”运算符的 System.Reflection.MethodInfo。
由于其实施,您不能执行以下操作:
if("hi" == 3) // compiler error, plus code would throw an exception even if it ran)
然而,同样的事情也适用于值类型:
if((int)1 == (float)1.0) // correctly returns true
if((int)1 == (float)1.2) // correctly returns false
我试图弄清楚 .NET 内部如何处理类型转换过程,所以我一直在寻找 .NET Reflector 中 op_Equality() 的实现,但“int”没有。
typeof(int).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public)
返回空值。
那么,值类型的“==”运算符的默认实现在哪里?我希望能够通过反射调用它:
public bool AreEqual(object x, object y)
{
if(x.GetType().IsValueType && y.GetType().IsValueType)
return x == y; // Incorrect, this calls the "object" equality override
else
...
}
编辑#1:
我试过这个,但没有奏效:
(int)1 == (float)1; // returns true
System.ValueType.Equals( (int)1, (float)1 ); // returns false
编辑#2:
也试过这个,但没有爱:
object x = (int)1;
object y = (float)1.0;
bool b1 = (x == y); // b1 = false
bool b2 = ((ValueType)x).Equals(y); // b2 = false
由于这种类型检查(从 .NET Reflector 中提取),我相信 ValueType 上的这个 .Equals 运算符不起作用:
ValueType.Equals(object obj)
{
...
RuntimeType type = (RuntimeType) base.GetType();
RuntimeType type2 = (RuntimeType) obj.GetType();
if (type2 != type)
{
return false;
}
...