加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实现IComparable

发布时间:2020-12-15 18:22:37 所属栏目:百科 来源:网络整理
导读:当我试图从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 convers
当我试图从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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读