144调用接口方法详解145接口方法的隐式和显式调用146泛型接口147泛型接口和接口约束148实现 144调用接口方法详解 145接口方法的隐式和显式调用 146泛型接口 147 泛型接口和接口约束 148实
144调用接口方法详解145接口方法的隐式和显式调用146泛型接口147泛型接口和接口约束148实现 144调用接口方法详解
145接口方法的隐式和显式调用
146泛型接口
147 泛型接口和接口约束
148实现具有多个方法名和签名的多个接口
149用显示接口方法实现改进编译时类型安全
class Program
{
public static void Main()
{
SomeValueType sv new SomeValueType(5);
Object o1 new object();
Int32 n sv.CompareTo(sv);//装箱操作
// n sv.CompareTo(o1);//编译通过出现运行时错误
OtherValueType ov new OtherValueType(5);
Object o2 new object();
n ov.CompareTo(ov);//没有进行装箱操作
// n ov.CompareTo(o2);//编译时错误
Console.WriteLine(n);
Console.ReadLine();
}
}
//未使用EIMI
internal struct SomeValueType : IComparable
{
private Int32 m_x;
public SomeValueType(Int32 x)
{
m_x x;
}
public Int32 CompareTo(Object other)
{
return (m_x - ((SomeValueType)other).m_x);
}
}
//使用EIMI
internal struct OtherValueType : IComparable
{
private Int32 m_x;
public OtherValueType(Int32 x)
{
m_x x;
}
public Int32 CompareTo(OtherValueType other)
{
return (m_x - other.m_x);
}
Int32 IComparable.CompareTo(Object other)
{
return CompareTo((OtherValueType)other);
}
} 1410谨慎使用显示接口方法实现
//
//internal class Base : IComparable {
// //显式接口方法
// Int32 IComparable.CompareTo(Object o) {
// Console.WriteLine("Base.ComparaTo");
// return 0;
// }
//}
//internal class Derived : Base,IComparable {
// //接口实现的公共方法
// public Int32 CompareTo(Object o){
// Console.WriteLine("Derived.ComparaTo");
// //调用基类的CompareTo会导致错误
// //base.CompareTo(o);
// return 0;
// }
//}
//正确定义Base和Derived
internal class Base : IComparable
{
//显式接口方法
Int32 IComparable.CompareTo(Object o)
{
Console.WriteLine("Bases IComparable ComparaTo");
return 0;
}
//基类的虚方法
public virtual Int32 CompareTo(Object o)
{
Console.WriteLine("Bases virtual ComparaTo");
return 0;
}
}
internal class Derived : Base, IComparable
{
//也是接口实现的公共方法
public override Int32 CompareTo(Object o)
{
Console.WriteLine("Derived.ComparaTo");
return base.CompareTo(o);
}
} 1411设计基类还是接口