因为struct是值类型,list的Contains和IndexOf判断的是元素是否相等。
例如下面的测试代码
using System.Collections.Generic;
using System.Numerics;
List<MyStruct> lists = new List<MyStruct>() { new MyStruct(1, 1), new MyStruct(2, 1) };
Console.WriteLine(lists.Contains(new MyStruct(2, 1)));
Console.WriteLine(lists.IndexOf(new MyStruct(2, 1)));
Console.WriteLine(lists.Contains(new MyStruct(1, 0)));
Console.WriteLine(lists.IndexOf(new MyStruct(4, 1)));
struct MyStruct
{
public int A;
public int B;
public MyStruct(int a, int b)
{
A = a;
B = b;
}
}
输出结果应为
image.png
网友评论