.Contains 适用于 .Equals 方法。默认情况下,.Equals 方法仅返回 true,如果两个实例(引用)相同。
解决这个问题的一种可能方法 - 如果因素的数量是固定的 - 是使用Tuple<int,int>。您可以在 `Tuple 类上定义 Reverse 方法:
public static class Foo {
public static Tuple<T2,T1> Reverse<T1,T2> (this Tuple<T1,T2> tuple) {
return new Tuple<T2,T1>(tuple.Item2,tuple.Item1);
}
}
然后简单地调用它:
Tuple<int,int> t = new Tuple<int,int>(3,5);
Tuple<int,int> t2 = t.Reverse();
如果不是,您可以定义一个 wrapper 类,该类执行 here 所述的相等性检查。
或者另一种选择是在.Contains 方法中自己提供一个相等检查器,如@xanatos answer 所述。
演示:
$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp> var t1 = new Tuple<int,int>(3,2);
csharp> var t2 = new Tuple<int,int>(3,2);
csharp> t1.Equals(t2);
true
csharp> int[] t1 = new int[] {3,2};
csharp> int[] t2 = new int[] {3,2};
csharp> t1.Equals(t2);
false