Skip to main content
 首页 » 编程设计

c#之在数组队列上使用 Contains 时,控制台返回 False。为什么

2024年02月06日14Terrylee

我创建了一个程序,其中有一个 int 数组队列:

Queue< int[] > Test = new Queue< int[] >(); 

给定一个数组,我想检查该数组是否在队列中。

我目前使用的命名空间是:System、System.Collections 和 System.Collections.Generic。

我试过这样的:

Queue<int[]> Test = new Queue<int[]>(); 
 
Test.Enqueue(new int[] { 20, 20 }); 
 
Console.WriteLine( Test.Contains(new int[] { 20, 20 }) ); // Is the array {20,20} inside the queue? 

在这段代码中,在我看来,控制台将输出“true”,因为我将数组 {20, 20} 添加到队列中,现在我正在使用 Contains 方法进行检查。

但是当我运行代码时——控制台输出 false。

我有两个问题: 为什么会这样?我该如何解决这个问题?

请您参考如下方法:

因为数组是引用类型,所以比较将基于引用。即使内容相同,您的数组也有不同的引用。这就是您得到 false 的原因。

要解决这个问题,您可以实现自定义比较器,或者您可以使用 LINQ 方法,例如

bool arrayExists = Test.Any(x => x.SequenceEqual(new[] { 20, 20 }));