摘要:(2010-08-02) C#.NET 實作 IEquatable 介面
類別
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mod01 { public class Employee:System.IComparable<Employee>,IEquatable<Employee> { //Data Field private Int32 _id; public Int32 Id { get { return _id; } set { _id = value; } } private Decimal _salary; public Decimal Salary { get { return _salary; } set { _salary = value; } } private String _name; public String Name { get { return _name; } set { _name = value; } } public Employee() { } //解構子 ~Employee() { //類別成員 AppUtil.writeMsg(@"c:\mylog.txt","Employee解構了!!"+DateTime.Now.ToString()); } #region IComparable<Employee> 成員 public int CompareTo(Employee other) { Int32 r = 0; // 相等 if (this.Id > other.Id) { r = 1; } if (this.Id < other.Id) { r = -1; } return r; } #endregion #region IEquatable<Employee> 成員 public bool Equals(Employee other) { Boolean r = false; if((this.Id==other.Id) && (this.Name.Equals(other.Name))) { r=true; } return r; } #endregion } }
主程式
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mod01 { class TestEmployeeEquals { public static void Main() { Employee emp1 = new Employee() { Id = 1, Salary = 50000, Name = "eric" }; Employee emp2 = new Employee() { Id = 1, Salary = 50000, Name = "eric" }; //兩個物件內容比對 if (emp1 == emp2) //比位址 { System.Console.WriteLine("相同!!"); } else { System.Console.WriteLine("不相同!!"); } if (emp1 .Equals(emp2)) //比位址 { System.Console.WriteLine("相同!!"); } else { System.Console.WriteLine("不相同!!"); } } } }
輸出
不相同!!
相同!!