gpt4 book ai didi

c# - ValueTypes 数组不喜欢 object.Equals?

转载 作者:行者123 更新时间:2023-11-30 13:27:37 24 4
gpt4 key购买 nike

这让我抓狂了好几天:

byte[] _A = new byte[64];
// Fill _A with some meaningful, valid data.

byte[] _B = new byte[_A.Length];
_A.CopyTo( _B, 0 );

if( !_A.Equals( _B ) ) {
throw new WtfException(
"It appears object.Equals doesn't work on arrays of value types...");
}

是的,这会抛出 WtfException。我花了几天时间才注意到。 byte 是一个 ValueType。但是,byte[] 是一个 System.Array,它是一个引用类型。根据 .NET 文档:

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

有人可以帮忙吗?

最佳答案

您比较的是引用类型(数组)而不是值类型。 _A 和 _B 确实不同 - 它们是两个不同的数组,但恰好包含相同的值。

关于c# - ValueTypes 数组不喜欢 object.Equals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9989931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com