在使用List的Contains、Remove方法时,如果List中成员的类型为自定义的类,要重载自定义类的Equals方法,Contains、Remove方法使用就会比较方便。

代码
 1 public class Pepole
 2 {
 3     public Pepole()
 4     {
 5     }
 6 
 7     public string Id { getset; }
 8 
 9     public string Name { getset; }
10 
11     public bool Equals(Pepole other)
12     {
13         return Id.Equals(other.Id);
14     }
15 
16     public override bool Equals(object obj)
17     {
18         if (obj is Pepole) return Equals((Pepole)obj);
19         return base.Equals(obj);
20     } 
21 }
22 
23 
24 
25     protected void Page_Load(object sender, EventArgs e)
26     {
27         List<Pepole> ls = new List<Pepole>();
28 
29         Pepole p1 = new Pepole();
30         p1.Id = "1";
31         p1.Name = "n1";
32         ls.Add(p1);
33 
34         Pepole p2 = new Pepole();
35         p2.Id = "2";
36         p2.Name = "n2";
37         ls.Add(p2);
38 
39         Pepole p3 = new Pepole();
40         p3.Id = "2";
41         p3.Name = "n2";
42 
43         bool b1 = ls.Contains(p3);
44 
45         ls.Remove(p3);
46         bool b2 = ls.Contains(p3);
47     } 


最终结果,b1为true,b2为false。

 

posted on 2009-12-05 16:16  znyin  阅读(2539)  评论(0编辑  收藏  举报