微软官方文档之基本类的构建
public class Customer: IComparable
{
// Used to control which field is used for comparisons.
private static CompareField m_CompareField;
public int Id;
public string Name;
public enum CompareField
{
Name,
Id
}
static Customer()
{
// Set the default compare field
m_CompareField = CompareField.Name;
}
public static void SetCompareKey(CompareField CompareKey)
{
// Change the comparison field
m_CompareField = CompareKey;
}
// Set default values by delegating to the next most complex constructor
public Customer():this(-1, "No Name")
{
}
public Customer(int newId, string newName)
{
this.Id = newId;
this.Name = newName;
}
public int CompareTo(object obj)
{
// First check to make sure we're only being compared to another customer.
if(obj.GetType().ToString() == "Customer")
{
// Create a strongly typed reference
Customerc = (Customer) obj;
// Determine if we should compare by Name or Id
if (Customer.m_CompareField == CompareField.Name)
{
return string.Compare(c.Name, this.Name, false);
}
else
{
if (c.Id == this.Id)
{
return 0;
}
else if (c.Id < this.Id)
{
return 1;
}
else
{
return -1;
}
}
}
else
{
throw new ArgumentException("Customers can only be compared against other customers. The object being passed in was a " + obj.GetType().ToString());
}
}
public override string ToString()
{
// Normally ToString returns the fully qualified typename.
// We are overriding it so that we can return a simple
// display string when we're added to a list box.
return string.Format("Id={0}, Name={1}", this.Id, this.Name);
}