日期:2014-05-20 浏览次数:20812 次
using System; using System.Collections; using System.Collections.Generic; namespace test0829 { class Person { public Person() { } public Person(string name) { this.Name = name; } public string Name{ get; set; } /// <summary> /// 重写ToString()方法 /// </summary> /// <returns></returns> public override string ToString() { return Name.ToString(); } /// <summary> /// 重写Equals()方法 /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (!(obj is Person)) { return false; } else return this.Name == ((Person)obj).Name; } //public override bool Equals(object obj) //{ // return base.Equals(obj); //} public override int GetHashCode() { return base.GetHashCode(); } } class Test { Person p1 = new Person("person1"); Person p2 = new Person("person2"); Person p3 = new Person("person1"); Person p4 = new Person("person4"); public void Eqtest() { Console.WriteLine(p1==p3); Console.WriteLine(p1.Equals(p3)); // base.Equals(p3); //Equals(p3); Console.WriteLine(Equals(p1,p3)); //Console.WriteLine(base.ToString()); //Console.WriteLine(Equals(p3)); } public void Listopt() { List<Person> li = new List<Person>(); li.Add(p1); li.Add(p2); Console.WriteLine("length= " + li.Count); foreach(Person p in li) { Console.WriteLine(p); } //li.RemoveAt(0); li.Remove(new Person("person1")); Console.WriteLine("length= "+li.Count); foreach (Person p in li) { Console.WriteLine(p); } } public void Hashsetopt(Person p) { HashSet<Person> ht = new HashSet<Person>(); //ht.Add(p1); //ht.Add(p2); //ht.Add(p3); //ht.Add(p4); if (!ht.Contains(p)) { ht.Add(p); } foreach(Person pe in ht) { Console.WriteLine(pe); } } } class Program { static void Main(string[] args) { //new Test().hashopt(); new Test().Listopt(); //new Test().Eqtest(); // new Test().Stringpot(); //new Test().Queueopt(); //new Test().Stackopt(); new Test().Hashsetopt(new Person("person1")); new Test().Hashsetopt(new Person("person1")); new Test().Hashsetopt(new Person("person2")); Console.Read(); } } }