TVP

# 在IEqualityComparer中包装委托

``````#region IEqualityComparer 使用示例
public static class ComparerHelper
{
public static IEqualityComparer<T> Create<T>(Func<T, T, int> compare) => new CustomEqualityComparer<T>(compare);

private class CustomEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, int> _compare;

public CustomEqualityComparer(Func<T, T, int> compare) => _compare = compare;

public bool Equals(T x, T y) => _compare(x, y) == 0;

public int GetHashCode(T obj) => obj.GetHashCode();
}
}

class Program
{
static void Main(string[] args)
{
int[] arr1 = { 1, 2, 3, 4 };
int[] arr2 = { 10, 20, 30, 40 };

Console.WriteLine("Without custom equality comparer:");
Array.Sort(arr1, Array.Equals<int>(arr1, arr2, (a, b) => a.CompareTo(b)));
Array.Sort(arr2, Array.Equals<int>(arr1, arr2, (a, b) => a.CompareTo(b)));

Console.WriteLine("With custom equality comparer:");
Array.Sort(arr1, new ComparerHelper.CustomEqualityComparer<(int x, int y)>((a, b) => a.Value.CompareTo(b)));
Array.Sort(arr2, new ComparerHelper.CustomEqualityComparer<(int x, int y)>((a, b) => a.Value.CompareTo(b)));

for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr2.Length; j++)
{
if(!arr1.Equals(arr2, new ComparerHelper.CustomEqualityComparer<(int x, int y)>((a, b) => a.Value.CompareTo(b)))))
Console.WriteLine(i + "," + j + ": The elements are not equal!");
}
}

}
}
#endregion``````

广告关闭
领券