在下面的例子中,据我所知,IComparable方法CompareTo被用作基本方法。我想在类中实现Interface方法(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();
}
}
}
答案 0 :(得分:2)
在
public class MyClass<T> where T : IComparable<T>
MyClass
类型未实现(或“继承”)IComparable<T>
,但它要求其类型参数T
执行。
在您的测试用例中,类型int
和string
是满足此约束的类型。
答案 1 :(得分:2)
必须实施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);
}