摘要:(2010-08-02) C#.NET 實作 ICloneable 介面
類別
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mod01
{
public class Employee:System.IComparable<Employee>,IEquatable<Employee>,ICloneable
{
//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
#region ICloneable 成員
public object Clone()
{
return new Employee(){ Id=this.Id, Name=this.Name, Salary=this.Salary};
}
#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" };
Employee emp3 = (Employee)emp1.Clone();
System.Console.WriteLine(emp3.Name);
}
}
}