== 使用反射的运算符 [英] == operator using reflection
问题描述
使用反射后的对象比较
var a = new A
{
a = "aa",
b = 1
};
var b = new A {
a = "aa",
b = 2
};
Type type = typeof(A);
object old = type.GetProperty("a").GetValue(a);
object Oldold = type.GetProperty("a").GetValue(b);
int one = 1;
int oneOne = 1;
object oneO = one;
object oneOneO = oneOne
// old == Oldold - true
// one == oneOne - true
// oneO == oneOneO - false
}
我希望 oneO == oneOneO 是真的.有人可以解释一下这里发生了什么吗?
I would expect that oneO == oneOneO is true. Can someone explain me what is going on here?
推荐答案
您是 装箱 int
通过将其分配给 Object
变量.这会创建一个新实例,并且 System.Object
中的 ==
比较引用,它们是不同的,所以它返回 false
.
You are boxing the int
by assigning it to an Object
variable. That creates a new instance and ==
in System.Object
compares references, they are different, so it returns false
.
如果您将其转换回(拆箱)为 int
,==
将按预期工作:
If you would cast it back(unbox) to an int
the ==
would work as expected:
object oneO = one;
object oneOneO = oneOne;
int newOne = (int) oneO;
int newOneOne = (int) oneOneO;
Console.WriteLine(newOne == newOneOne); // true
如果您使用 Equals
而不是 ==
,它们也会按预期进行比较,因为 System.Int32
覆盖Equals
有意义.
If you would use Equals
instead of ==
they would also be compared as expected because System.Int32
overrides Equals
meaningfully.
old
和Oldold
是没有装箱的引用类型(字符串),只有值类型- 但是字符串是一种特殊的引用类型,它重载了相等运算符(进一步阅读)
old
andOldold
are reference types(string) which are not boxed, only value types- But string is a special reference type which overloads the equality operator(read further)
根据经验:如果您使用引用类型,请小心使用 ==
运算符.System.String
重载相等运算符 例如.但这是一个例外.通常你只是比较参考.装箱基本上使值类型成为引用类型,但这是一个隐藏的实现细节(即使 oneO.GetType().IsValueType
仍然返回 true
).
As a rule of thumb: if you use reference types be careful with the ==
operator. System.String
overloads the equality operator for example. But that is an exception. Normally you are just comparing references. Boxing basically makes the value type a reference type, but that's a hidden implementation detail(even oneO.GetType().IsValueType
still returns true
).
另请注意,如果您有这样的方法,也会发生这种装箱转换:
Also note that this boxing conversion also takes place if you have a method like this:
public static bool SameThings(object obj1, object obj2)
{
return obj1 == obj2;
}
我希望你不会再对输出 false
感到惊讶:
I hope you are not anymore surprised that this outputs false
:
Console.WriteLine(SameThings(1, 1)); // false
这篇关于== 使用反射的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!