繁体   English   中英

IComparable的 <T> 继承还是接口?

[英]IComparable<T> Inheritance or Interface?

在下面的示例中,据我了解,IComparable方法CompareTo用作基本方法。 我想知道在类中实现接口方法(CompareTo)是否是强制性的吗? 下面的示例未执行此操作。 刚用过。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
public class MyClass<T> where T : IComparable<T>
{
    public void GetBiggerValue(T Value1, T Value2)
    {
        if (Value1.CompareTo(Value2) > 0)
        {
            Console.WriteLine("{0} is bigger than {1}", Value1, Value2);
        }

        if (Value1.CompareTo(Value2) == 0)
        {
            Console.WriteLine("{0} is equal to {1}", Value1, Value2);
        }

        if (Value1.CompareTo(Value2) < 0)
        {
            Console.WriteLine("{0} is smaller than {1}", Value1, Value2);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();

        MyClass<int> mcInt = new MyClass<int>();
        MyClass<string> mcString = new MyClass<string>();

        mcInt.GetBiggerValue(124, 126);             //126          

        Console.ReadKey();
    }
}
}

 public class MyClass<T> where T : IComparable<T>

MyClass类型不实现(或“继承”) IComparable<T>但它要求其Type Parameter T实现。

在您的测试用例中,类型intstring是满足此约束的类型。

必须实现IComparable<T>T ,但不是MyClass<T> IComparable<T>

 where T : IComparable<T> // <- It is T that's restricted

在您的情况下:

 // T == int; int is comparable (implements IComparable<int>)
 MyClass<int> mcInt = ...

 // T == string; string is comparable (implements IComparable<string>)
 MyClass<string> mcString = ...

如果放置MyClass<int[]>int[]不实现IComparable<int[]> ),则会出现编译时错误。

编辑:当前的实现存在一些问题:

// Technically, you don't want any MyClass<T> instance
//TODO: change into static: public static void GetBiggerValue(T Value1, T Value2
public void GetBiggerValue(T Value1, T Value2) {
  //DONE: Value1 can well be null; Value1.CompareTo(...) will throw exception then
  //DONE: CompareTo can be expensive, compute it once
  int compare = (null == Value1) 
    ? (null == Value2 ? 0 : -1) // null equals to null, but less any other value
    : Value1.CompareTo(Value2);

  // A shorter alternative is 
  // int compare = Comparer<T>.Default.Compare(Value1, Value2);

  //DONE: if ... else if is more readable construction in the context 
  if (compare > 0) 
    Console.WriteLine("{0} is bigger than {1}", Value1, Value2);
  else if (compare < 0)
    Console.WriteLine("{0} is smaller than {1}", Value1, Value2);
  else  
    Console.WriteLine("{0} is equal to {1}", Value1, Value2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM