微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 实现IComparable

当我试图从Jon Skeet的书C#深入调整清单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;
          }
         }
}

如何添加像“狗”这样的引用类型来使用Jon Skeets代码列表???我知道Dog需要实现IComparable但我不知道怎么做!

解决方法

您可以通过说明需要类型T来定义方法,类型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.

原文地址:https://www.jb51.cc/csharp/98334.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐