Csharp/CSharp Tutorial/Class/IEquatable — различия между версиями

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

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

A class which implements comparison and equality interfaces

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
class Person : IComparable<Person>, IEquatable<Person>, IComparable
{
    public string Name;
    public int Age;
    public string Company;
    // Implements IComparable<Person>.rupareTo:
    public int CompareTo(Person other)
    {
        if (other == null)
            return -1;
        return this.Name.rupareTo(other.Name);
    }
    // Implements IComparable.rupareTo:
    public int CompareTo(object obj)
    {
        Person p = obj as Person;
        return CompareTo(p);
    }
    // Implements IEquatable<Person>.Equals:
    public bool Equals(Person other)
    {
        return ((IComparable<Person>)this).rupareTo(other) == 0;
    }
    // Overrides Object.Equals:
    public override bool Equals(object obj)
    {
        Person p = obj as Person;
        return Equals(p);
    }
}
public class MainClass
{
    public static void Main()
    {
        Person[] people = new Person[3];
        people[0] = new Person();
        people[0].Name = "S D"; people[0].Age = 20; people[0].rupany = "E";
        people[1] = new Person();
        people[1].Name = "M M"; people[1].Age = 40; people[1].rupany = "C";
        people[2] = new Person();
        people[2].Name = "J D"; people[2].Age = 30; people[2].rupany = "T";
        foreach (Person p in people)
            Console.Write(""{0},{1},{2}"\t", p.Name, p.Age, p.rupany);
        Console.WriteLine();
        Array.Sort(people);
        foreach (Person p in people)
            Console.Write(""{0},{1},{2}"\t", p.Name, p.Age, p.rupany);
    }
}
"S D,20,E"      "M M,40,C"      "J D,30,T"
"J D,30,T"      "M M,40,C"      "S D,20,E"