public static void Main(string[] args)
        {

            Product p1 = new Product{Id=1001};
            Product p2 = new Product{Id=1002};

            List<Product> list = new List<Product>();
            list.Add(p1);
            list.Add(p2);

            Product p3 = new Product { Id = 1002 };
            if (list.Contains(p3))
            {
                list.Remove(p3);
            }

            Product p4 = new Product { Id = 1001, Name = "tony" };
            if (!list.Contains(p4))
            {
                list.Add(p4);
            }


          
            System.Diagnostics .Debugger .Break ();
        }

 

------------------------

 

 public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }

      
        public override bool Equals(System.Object obj)
        {
            // If parameter is null return false.
            if (obj == null)
            {
                return false;
            }

            // If parameter cannot be cast to Point return false.
            Product p = obj as Product;
            if ((System.Object)p == null)
            {
                return false;
            }

            // Return true if the fields match:
            return this.Id == p.Id;
        }


        public static bool operator ==(Product product1, Product product2)
        {
            // If both are null, or both are same instance, return true.
            if (System.Object.ReferenceEquals(product1, product2))
            {
                return true;
            }
            // If one is null, but not both, return false.
            if (((object)product1 == null) || ((object)product2 == null))
            {
                return false;
            }

            // Return true if the fields match:
            return product1.Id == product2.Id;
        }

        public static bool operator !=(Product product1, Product product2)
        {
            // Return true if the fields match:
            return product1 != product2;
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode() ;
        }
    }

posted on 2011-06-21 13:36  tonylx  阅读(480)  评论(0)    收藏  举报