请教高手C#,报错IComparable接口成员无法实现,但IEquatbale 成员可以,不知为何?已重写GetHashCode
using System;
class MyClass : IComparable<MyClass>, IEquatable<MyClass> {
public int val;
public MyClass(int v) { val = v; }
public int compareTo(MyClass otherValue) {
return val - otherValue.val;
}
public bool Equals(MyClass otherValue) {
return val == otherValue.val;
}
public override bool Equals(object obj)
{
if(obj is MyClass)
return Equals((MyClass) obj);
return false;
}
public override int GetHashCode()
{
return val.GetHashCode();
}
}
class Demo {
public static bool IsIn<T>(T what, T[] obs) where T : IEquatable<T> {
foreach (T v in obs) if (v.Equals(what)) return true;
return false;
}
public static bool Inrange<T>(T what, T[]obs)where T: IComparable<T>{
if (what.CompareTo(obs[0]) < 0 || what.CompareTo(obs[obs.Length - 1]) > 0) return false; return true;
}
static void Main() {
int[] mums = { 1, 2, 3, 4, 5 };
if (IsIn(2, mums)) Console.WriteLine("2 is found");
if (Inrange(2, mums)) Console.WriteLine("2 is in range");
}
}
------解决方案--------------------
呵呵,因为你把方法名中字母C写成小写了。
尽量不要手写代码。你可以在接口上点击鼠标右键,使用vs的“重构->实现接口”选项,让vs自动给你生成代码,这样就不会把字母C写成c了。