代码清单3-6 表示一对值泛型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Pair<int, string> pair = new Pair<int, string>(10, "value");
            Pair<int, string> pair1 = new Pair<int, string>(10, "value");
            bool isEqual = pair.Equals(pair1);
            Console.ReadKey();
        }
    }

    public sealed class Pair<T1, T2> : IEquatable<Pair<T1, T2>>
    {
        private static readonly IEqualityComparer<T1> firstComparer = EqualityComparer<T1>.Default;
        private static readonly IEqualityComparer<T2> secondComparer = EqualityComparer<T2>.Default;
        private readonly T1 first;
        private readonly T2 second;
        public Pair(T1 first, T2 second)
        {
            this.first = first;
            this.second = second;
        }

        public T1 First { get { return this.first; } }
        public T2 Second { get { return this.second; } }

        public bool Equals(Pair<T1, T2> other)
        {
            return other != null && firstComparer.Equals(this.First, other.First) && secondComparer.Equals(this.Second, other.Second);
            //return other != null && this.First.Equals(other.First) && this.Second.Equals(other.Second);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Pair<T1, T2>);
        }

        public override int GetHashCode()
        {
            return firstComparer.GetHashCode(First) * 37 + secondComparer.GetHashCode(Second);
        }
    }
}

  

原文地址:https://www.cnblogs.com/liuslayer/p/6928130.html