[英]Object.ReferenceEquals never hit
Can anyone tell me why the following condition does not hit? 谁能告诉我为什么以下情况不会发生?
List<DateTime> timestamps = new List<DateTime>();
timestamps.Add(DateTime.Parse("8/5/2011 4:34:43 AM"));
timestamps.Add(DateTime.Parse("8/5/2011 4:35:43 AM"));
foreach(DateTime x in timestamps)
{
if (Object.ReferenceEquals(x, timestamps.First()))
{
// Never hit
Console.WriteLine("hello");
}
}
Because DateTime is a value type, immutable and so the references will not be equal even though the values are. 因为DateTime是一个值类型,不可变,所以即使值是引用也不相等。
Are you meaning to do something like this? 你有意这样做吗? Value comparison:
价值比较:
if (DateTime.Compare(x, timestamps.First()) == 0)
{
// Never hit
Console.WriteLine("hello");
}
Value types are passed and compared by value . 传递值类型并按值进行比较。 That's why they're called "value types".
这就是为什么他们被称为“价值类型”。
Reference types are passed and compared by reference . 参考类型通过引用传递和比较。 That's why they're called "reference types".
这就是为什么他们被称为“参考类型”。
DateTime is a value type . DateTime是值类型 。
Therefore you are attempting to compare two values by reference . 因此,您试图通过引用比较两个值。 That's not going to work.
那不行。 It will always be false.
它总是假的。
Can you explain why you'd expect something different? 你能解释为什么你会期待不同的东西吗?
I think that a number of the other answers miss something. 我认为其他一些答案会遗漏一些东西。
In the case of object.ReferenceEquals(object,object)
any value-types are "boxed" to objects and it is these (new) objects which are passed. 在
object.ReferenceEquals(object,object)
的情况下,任何值类型都被“装箱”到对象,并且这些(新)对象被传递。 Consider the following: 考虑以下:
DateTime d1 = DateTime.MinValue;
DateTime d2 = d1;
object ob1 = (object)d1; // boxed!
object ob2 = ob1;
// false - the values in d1 and d2 are BOXED to (new) different objects
object.ReferenceEquals(d1, d2);
// false - same as above, although I am not sure sure if a
// VM implementation could re-use a BOXED object
object.ReferenceEquals(d1, d1);
// true - naturally - BOXED only once at "boxed!" (same object!)
object.ReferenceEquals(ob1, ob2);
Happy coding. 快乐的编码。
Related: Marc's answer in Value Type Vs Reference Type - Object Class C# where he talks about a boxing conversion . 相关:Marc在Value Type Vs中的答案参考类型 - 对象类C# ,他谈到了拳击转换 。
They have the same value, but they aren't the same reference. 它们具有相同的值,但它们不是相同的参考。
Take a look at the MSDN entry for Object.ReferenceEquals
查看
Object.ReferenceEquals
的MSDN条目
Furthermore, even if you had been comparing the same object, you would still not hit it by comparing the references, because DateTime
is a structure, that is, it is value type. 此外,即使你一直在比较同一个对象,你仍然不会通过比较引用来命中它,因为
DateTime
是一个结构,也就是说它是值类型。 Value Types
, by definition, copy the contained value, not the reference to the object (like Reference Types
do). 根据定义,
Value Types
复制包含的值,而不是对象的引用(如Reference Types
一样)。
对象首先在ReferenceEquals中复制,因为它们是值类型,因此引用永远不会相等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.