}
}
class IComparableDemo { static void Main() {
ArrayList inv = new ArrayList();
inv.Add(new Inventory("", 5.95, 3)); inv.Add(new Inventory("", 8.29, 2)); inv.Add(new Inventory("", 3.50, 4)); inv.Add(new Inventory("", 19.88, 8));
Console.WriteLine(" :"); foreach(Inventory i in inv) {
^Console.WriteLine(" " + i);
} '
Console.WriteLine();
// , inv.Sort();
Console.WriteLine(" :"), foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
}
}
. , Sort () .
:
IComparable
, , IComparable<T>. IComparable CompareTo ().
int CompareTo( other)
CompareTo () other. , ; , other; , other. . IComparable<T> .
, IComparable<T>. List<T> ArrayList.
// IComparable<T>. using System;
Using System.Collections.Generic;
// IComparable<T>. class Inventory: IComparable<Inventory> { string name; double cost; int onhand;
public Inventory(string n, double c, int h) { name = n; cost = c; onhand = h;
}
public override string ToString() { return
String.Format("{0,-10}: {1,6:C} : {2}", name, cost, onhand);
}
// IComparable<T>. public int CompareTo(Inventory obj) { return name.CompareTo(obj.name);
}
}
class GenericIComparableDemo { static void Main() {
List<Inventory> inv = new List<Inventory>();
// . inv.Add(new Inventory("", 5.95, 3)); inv.Add(new Inventory("", 8.29, 2)); inv.Add(newInventory("", 3.50, 4)); inv.Add(new Inventory("", 19.88, 8 );
|
|
Console.WriteLine(" :"); foreach(Inventory i in inv) {
Console.WriteLine (" " + i);
}
Console.WriteLine ();
// , inv.Sort ();
Console.WriteLine(" :"); foreach(Inventory i in inv) {
Console.WriteLine (" " + i);
}
}
}
, , .
IComparer
IComparable. IComparer. , IComparer, , .
IComparer : . , , , , .
icomparer