实现 IComparable 接口的 C# 程序
C# 提供了一个 IComparable 接口。该接口提供了不同类型的特定类型比较方法,这意味着值类型或类可以实现该接口来对其实例进行排序,因为我们无法直接对类的实例进行排序,因为编译器不知道在哪个基础上进行排序。同样,直接比较两个实例会引发编译器错误,因为编译器对要比较的内容感到困惑。
句法:
public interface IComparable
实现 IComparable 接口需要:
- 添加一个方法 CompareTo(),它接收一个对象并返回一个整数。
- 传入的对象首先被类型转换为类类型并存储在临时变量中。然后将其与当前方法的属性进行比较
- CompareTo() 方法取决于比较:
- 如果当前实例的属性等于临时变量的属性,则返回 0
- 如果当前实例的属性大于临时变量的属性,则返回 1
- 如果当前实例的属性小于临时变量的属性,则返回 -1
现在让我们通过下面的示例讨论如何实现 IComparable 接口。
示例:下面是 IComparable 接口的实现。在此示例中,我们根据员工 ID 对员工进行排序。
C#
// C# program to demonstrate how to
// implement IComparable interface
using System;
using System.Collections.Generic;
class GFG{
// Driver code
static public void Main()
{
// Create an array of employees
// using collection initializer
Employee[] employees = new Employee[]
{
new Employee(1, "Susmita"),
new Employee(5, "Soniya"),
new Employee(3, "Rohit"),
new Employee(2, "Mohit"),
new Employee(4, "Pihu")
};
// Displaying the employee's array before sorting
Console.WriteLine("Before sorting employees array");
foreach(var emp in employees)
{
Console.WriteLine("ID - {0}, Employee Name - {1}",
emp.ID, emp.EmployeeName);
}
// Sorts the employees array in ascending
// order on basis of id of the employee
Array.Sort(employees);
Console.WriteLine();
// Printing the employee's array after sorting
Console.WriteLine("After sorting employees array");
foreach(var emp in employees)
{
Console.WriteLine("ID - {0}, Employee Name - {1}",
emp.ID, emp.EmployeeName);
}
}
}
// Implementing IComparable interface
public class Employee : IComparable{
public int ID;
public string EmployeeName;
// Employee constructor
public Employee(int id, string employeename)
{
this.ID = id;
this.EmployeeName = employeename;
}
// Implementation of the CompareTo() method which takes
// an object as an input and return integer value depending on
// the comparison between current object and incoming object,
public int CompareTo(object incomingobject)
{
// Storing incoming object in temp variable of
// current class type
Employee incomingemployee = incomingobject as Employee;
return this.ID.CompareTo(incomingemployee.ID);
}
}
输出:
Before sorting employees array
ID - 1, Employee Name - Susmita
ID - 5, Employee Name - Soniya
ID - 3, Employee Name - Rohit
ID - 2, Employee Name - Mohit
ID - 4, Employee Name - Pihu
After sorting employees array
ID - 1, Employee Name - Susmita
ID - 2, Employee Name - Mohit
ID - 3, Employee Name - Rohit
ID - 4, Employee Name - Pihu
ID - 5, Employee Name - Soniya