例如
class UseInerface:IComparable
{
private int num;
public UseInerface(int num)
{
this.num=num;
}
public int CompareTo(Object obj) //重写CompareTo函数
{
UseInerface otherObject=obj as UseInerface;
if(otherObject==null)
throw new ArgumentException("error");
if(num<otherObject.num) //使用私有成员num
return -1;
else if(num>otherObject.num)
return 1;
else
return 0;
}
}
class Test
{
public static int Main()
{
UseInerface class1=new UseInerface(1);
UseInerface class2=new UseInerface(2);
Console.WriteLine(class1.CompareTo(2)); return(0);
}
}
class UseInerface:IComparable
{
private int num;
public UseInerface(int num)
{
this.num=num;
}
public int CompareTo(Object obj) //重写CompareTo函数
{
UseInerface otherObject=obj as UseInerface;
if(otherObject==null)
throw new ArgumentException("error");
if(num<otherObject.num) //使用私有成员num
return -1;
else if(num>otherObject.num)
return 1;
else
return 0;
}
}
class Test
{
public static int Main()
{
UseInerface class1=new UseInerface(1);
UseInerface class2=new UseInerface(2);
Console.WriteLine(class1.CompareTo(2)); return(0);
}
}
接口只是对一个类应该有些什么方法做出规范,而具体实现是由该类自己实现的,所以和他直接写一个这样的方法也没什么不同的,自然可调用它的私有成员。
另外你写得是不是应该为public override int CompareTo(Object obj)才能编译通过?