c# - 用字符串实现 IComparable

标签 c# string interface icomparable

我有 Employee 类,我需要实现 IComparable 并使用 CompareTo 方法按姓名对员工进行排序。据我所知,我必须返回 1、-1 和 0,但我该如何使用这些字符串?

这是我的。

class Employee : IComparable<Employee>
{
    string name;
    string address;

    public int CompareTo(Employee obj) 
    {
        Employee person = obj;
    }
}

最佳答案

最简单的方法就是将它传递给一个已经实现的比较方法。在这种情况下,由于您只需要比较两个字符串,您可以调用 String.Compare:

class Employee : IComparable<Employee>
{
    string name;
    string address;

    public int CompareTo(Employee obj) 
        => string.Compare(name, obj.name);    
}

您也可以使用 name.CompareTo(obj.name),但是您需要担心 name 是否可能为 null。根据the MSDN articleString.Compare 上:

One or both comparands can be null. By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

关于c# - 用字符串实现 IComparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44580026/

相关文章:

c# - 给定当前 URL,是否有内置的从相对路径(例如 "~/page.aspx")创建绝对(完全限定)URL?

C# 验证日期模式

c# - 检查并返回字符串列表中的关键字

c - 对 gets_s 的 undefined reference

c++ - 字符串重复由连字符c++替换

java - 更改第三方 jar 的版本是否需要重新编译我的代码?

Activity中的Java类调用方法

java - 反序列化 GSON 中的接口(interface)

c# - 如何从代码后面关闭选项卡?

javascript - C# ListItemCollection 到 JSON,同时保留值和文本项