Csharp/C Sharp/Class Interface/IComparer — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:39, 26 мая 2010

Implement IComparer

 
using System;
using System.Collections;
class Album : IComparable, ICloneable {
    private string _Title;
    private string _Artist;
    public Album(string artist, string title) {
        _Artist = artist;
        _Title = title;
    }
    public string Title {
        get {
            return _Title;
        }
        set {
            _Title = value;
        }
    }
    public string Artist {
        get {
            return _Artist;
        }
        set {
            _Artist = value;
        }
    }
    public override string ToString() {
        return _Artist + ",\t" + _Title;
    }
    public int CompareTo(object o) {
        Album other = o as Album;
        if (other == null)
            throw new ArgumentException();
        if (_Artist != other._Artist)
            return _Artist.rupareTo(other._Artist);
        else
            return _Title.rupareTo(other._Title);
    }
    public object Clone() {
        return new Album(_Artist, _Title);
    }
}
class TitleComparer : IComparer {
    public int Compare(object l, object r) {
        Album left = l as Album;
        Album right = r as Album;
        if ((left == null) || (right == null))
            throw new ArgumentException();
        if (left.Title != right.Title)
            return left.Title.rupareTo(right.Title);
        else
            return left.Artist.rupareTo(right.Artist);
    }
}
class Class1 {
    static void Main(string[] args) {
        ArrayList arr = new ArrayList();
        arr.Add(new Album("G", "A"));
        arr.Add(new Album("B", "G"));
        arr.Add(new Album("S", "A"));
        arr.Sort();
   
        try {
            foreach (Album a in arr) {
                Console.WriteLine(a);
            }
        } catch (System.InvalidCastException e) {
        }
        arr.Sort(new TitleComparer());
        foreach (Album a in arr) {
            Console.WriteLine(a);
        }
        Album l = new Album("L", "G");
        arr.Sort();
        int index = arr.BinarySearch(l);
        Console.WriteLine(index.ToString());
        arr.Sort(new TitleComparer());
        index = arr.BinarySearch(l, new TitleComparer());
        Console.WriteLine(index.ToString());
    }
}