Compare().
Int Compare(object x, object y)
Compare () x . , ; , ; , . . , CompareTo () ArgumentException.
IComparer SortedList, ArrayList. Sort (IComparer), . IComparer , , IComparable .
, IComparer . Comp Inv, IComparer Inventory. Complnv Sort () .
Using System;
Using System.Collections;
// IComparer Inventory, class CompInv: IComparer {
// IComparer. public int Compare(object x, object y) {
Inventory, a, b; a = (Inventory) x; b = (Inventory) y;
Return string.Compare(a.name, b.name, StringComparison.Ordinal);
}
}
class Inventory { public string name; double cost; int onhand;
public Inventory(string n, double c, int h) { name = n; cost = c; onhand = h;
}
public override string ToStringO { return
String.Format("{0,-10} : {1,6:} : {2}",
Name, cost, onhand);
}
}
class IComparerDemo { static void Main() {
Complnv comp = new CompInv();
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();
// , IComparer. inv.Sort(comp);
Console.WriteLine(" :"); foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
}
}
, .
1<>
|
|
IComparer<T> IComparer. Compare ().
Int Compare( , )
, ; , ; , .
, I Comparer <>. , .
// IComparer<T>. using System;
Using System.Collections.Generic;
// IComparer<T> Inventory, class CompInv<T>: IComparer<T> where T: Inventory {
// IComparer<T>. public int Compare(T x, T y) {