IComparable<T>, IComparer<T>,IEnumerable<T>泛型接口

本文介绍了C#中IComparable&lt;T&gt;和IComparer&lt;T&gt;泛型接口的应用,通过示例展示了如何实现自定义类型的比较逻辑,并通过IEnumerable&lt;T&gt;接口实现了自定义类型的迭代功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、IComparable<T>泛型接口

IComparable<T>泛型接口:定义由值类型或类实现的通用的比较方法,以为排序实例创建类型特定的比较方法。在这个接口中需要实现CompareTo(T)方法。

这个接口中的方法用于将当前实例与另一个对象比较大小,一个类如果实现了这个接口中的CompareTo方法,意味着这个类的对象时可比较的,它返回一个整型的返回值,返回值的含义如下。

如果返回值小于0,则当前实例小于比较对象。

如果返回值大于0,则当前实例大于比较对象。

如果返回值等于0,则当前实例等于比较对象。

示例:

创建Student.cs类并实现IComparable<T>泛型接口。

public class Student : IComparable<Student>
{
    public Student(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }

    public string Name { get; set; }
    public int Age { get; set; }

    //IComparable<Student> 成员
    public int CompareTo(Student other)
    {
        //按照学生的年龄进行排序
        if (this.Age < other.Age)
            return -1;
        else if (this.Age == other.Age)
            return 0;
        else
            return 1;

        //按照学生的姓名进行排序
        //return this.Name.CompareTo(other.Name);
    }
}

static void Main(string[] args)
{
    Student stu1 = new Student("Peter", 18);
    Student stu2 = new Student("Kevin", 15); 
    Student stu3 = new Student("Anne", 16);

    List<Student> stuList = new List<Student>();
    stuList.Add(stu1);
    stuList.Add(stu2);
    stuList.Add(stu3);

    Console.WriteLine("排序前:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("姓名:{0}、年龄:{1}", stu.Name, stu.Age);
    }

    stuList.Sort();   //使用默认排序
    Console.WriteLine("排序后:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("姓名:{0}、年龄:{1}", stu.Name, stu.Age);
    }
    Console.Read();
}

2、IComparer<T>泛型接口

IComparer<T>泛型接口:定义类型为比较两个对象而实现的方法。称为比较器,如果将不同的比较器传入Sort()方法就可以实现不同的比较方式。

IComparer<T>泛型接口,它有一个未实现的方法int Compare(T x, T y),它用于比较两个对象的大小。按照指定的方式比较大小,然后传入Sort()方法,就能事项这种比较方式的排序。它同样有一个整型的返回值,返回值的意义如下。

如果返回值大于0,则x>y。

如果返回值小于0,则x<y。

如果返回值等于0,则x=y。

示例:

创建Student.cs类并实现各种比较器。

public class Student
{
    public Student(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }

    public string Name { get; set; }
    public int Age { get; set; }
}

/*******************实现各种比较器*******************/
//姓名比较器升序
public class NameComparer : IComparer<Student>
{ 
    //实现姓名升序比较
    public int Compare(Student x, Student y)
    {
        return (x.Name.CompareTo(y.Name));
    }
}

//姓名比较器降序
public class NameComparerDesc : IComparer<Student>
{
    //实现姓名降序比较
    public int Compare(Student x, Student y)
    {
        return (y.Name.CompareTo(x.Name));
    }
}

//年龄比较器
public class AgeComparer : IComparer<Student>
{
    //实现姓名降序比较
    public int Compare(Student x, Student y)
    {
        return (x.Age.CompareTo(y.Age));
    }
}

static void Main(string[] args)
{
    Student stu1 = new Student("Peter", 18);
    Student stu2 = new Student("Kevin", 15); 
    Student stu3 = new Student("Anne", 16);

    List<Student> stuList = new List<Student>();
    stuList.Add(stu1);
    stuList.Add(stu2);
    stuList.Add(stu3);

    stuList.Sort(new NameComparer());
    Console.WriteLine("按姓名升序:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("姓名:{0}、年龄:{1}", stu.Name, stu.Age);
    }

    stuList.Sort(new NameComparerDesc());
    Console.WriteLine("按姓名降序:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("姓名:{0}、年龄:{1}", stu.Name, stu.Age);
    }

    stuList.Sort(new AgeComparer());
    Console.WriteLine("按年龄排序:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("姓名:{0}、年龄:{1}", stu.Name, stu.Age);
    }

    Console.Read();
}

3、IEnumerable<T>泛型接口

IEnumerable<T>泛型接口:公开枚举数,该枚举数支持在指定类型的集合上进行简单迭代。

示例:

创建Student.cs类并实现迭代功能。

public class Student : IEnumerable<Student>
{
    public Student(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }

    public string Name { get; set; }
    public int Age { get; set; }

    private Student[] _student;
    public Student(Student[] sArray)
    {
        _student = new Student[sArray.Length];
        for (int i = 0; i < sArray.Length; i++)
        {
            _student[i] = sArray[i];
        }
    }

    //IEnumerable<Student> 成员
    public IEnumerator<Student> GetEnumerator()
    {
        return new StudentEnum(_student);
    }

    //IEnumerable 成员
    IEnumerator IEnumerable.GetEnumerator()
    {
        return new StudentEnum(_student);
    }
}

public class StudentEnum : IEnumerator<Student>
{
    public Student[] _student;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    int position = -1;

    public StudentEnum(Student[] list)
    {
        _student = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _student.Length);
    }

    public void Reset()
    {
        position = -1;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Student Current
    {
        get
        {
            try
            {
                return _student[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }

    //IDisposable 成员
    public void Dispose() { }
}

static void Main(string[] args)
{
    Student[] studentArray = new Student[3]
    {
        new Student("Peter", 18),
        new Student("Kevin", 15),
        new Student("Anne", 16),
    };

    Student studentList = new Student(studentArray);
    foreach (Student stu in studentList)
    {
        Console.WriteLine("姓名:{0}、年龄:{1}", stu.Name, stu.Age);
    }
    Console.Read();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pan_junbiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值