c# - 实现 IComparable<T>

标签 c# generics

当我尝试调整 Jon Skeet 的书 C# in depth 中的 list 3.4 时,我收到以下错误消息...

The type 'list_3_4.Dog' cannot be used as type parameter 'T' in the generic type or method 'list_3_4.Program.CompareToDefault(T)'. There is no implicit reference conversion from 'list_3_4.Dog' to 'System.IComparable'.

这是我的代码...

using System;

namespace list_3_4
{
     class Program
     {
          static void Main(string[] args)
          {
               //string mystring;
               Dog d = new Dog("howie");

               Console.WriteLine(CompareToDefault("x"));
               Console.WriteLine(CompareToDefault(10));
               Console.WriteLine(CompareToDefault(0));
               Console.WriteLine(CompareToDefault(-10));              
               Console.WriteLine(CompareToDefault(DateTime.MinValue));

               Console.WriteLine(CompareToDefault(d));

               Console.ReadKey();
          }

          static int CompareToDefault<T> (T value) where T: IComparable<T>
          {
               return value.CompareTo(default(T));               
          }

     }

     public class Dog 
     {
          private string _name;

          public Dog(string name)
          {
               _name = name;
          }
         }
}

如何添加引用类型(如“Dog”)以使用 Jon Skeets 代码 list ???我知道 Dog 需要实现 IComparable 但我不知道如何实现!

最佳答案

你通过说你需要一个类型来定义方法 T那是一个IComparable<T> :

where T: IComparable<T>

但是Dog不执行 IComparable<Dog>

你需要做的:

public class Dog : IComparable<Dog>
{
 //this will allow you to do a quick name comparison
 public string Name { get; set;}
 public int CompareTo(Dog other)
 {//compare dogs by name
        return this._name.CompareTo(other.Name);
 }
}

注意:default(T)将为引用类型返回 null,因此您应该在某处进行 null 检查。了解 default on msdn .

关于c# - 实现 IComparable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12748232/

相关文章:

c# - 如何获取泛型类型的类型参数?

c# - 如何使用类型参数从泛型类型中提取原始泛型类型

java - 为什么允许 "extends T"但不允许 "implements T"?

c# - 是否可以在 c# 中创建一个合并接口(interface)的工厂?

c# - 这段代码可以简化吗?

c# - ArrayList 是数组还是列表?

java - 类型为 'super' 的有界泛型方法

c++ - 类模板 - 找不到合适的运算符方法

c# - resharper "Cannot resolve symbol"代码编译好时

c# - 使列不可为空,EF 外键错误