您的位置:首页 > 编程语言 > C#

C#框架阅读笔记--类和接口的继承

2011-11-11 11:43 323 查看
类和接口的继承

Framwork类库中几个接口的定义如下:

public interface IDisposiable

{

void Dispose();

}

public interface IEnumerable

{

IEnumerator GetEnumerator();

}

public interface IEnumerable<T> : IEnumerable

{

IEnumerator<T> GetEnumerator();

}

public interface ICollection<T> : IEnumerable<T>, IEnumerable

{

void Add(T item);

void Clear();

Boolean Contains(T item);

void Copyto(T[] array, Int32 arrayIndex);

Boolean Remove(T item);

Int32 Count

{

get;

}

Boolean IsReadOnly

{

get;

}

}

接口的继承:

System.IComparable<T>接口的定义如下:

public interface IComparable<T>

{

Int32 CompareTo(T other);

}

以下代码展示了如何定一个实现了该接口的类型,同时还展示了对两个point对象进行比较的代码:

using System;

//Point 继承自System.Object 并实现Point的IComparable<T>

public sealed class Point : IComparable<Point>

{

private Int32 m_x;

private Int32 m_y;

public Point(Int32 x, Int32 y)

{

m_x = x;

m_y = y;

}

//该方法实现了Point的IComparable<T>

public Int32 compareTo(Point other)

{

return Math.Sign(Math.Sqrt(m_x * m_x + m_y * m_y) - Math.Sqrt(other.m_x * other.m_x + other.m_y * other.m_y));

}

public override String ToString()

{

return String.Format("({0}, {1})", m_x, m_y);

}

}

public static class Program

{

public static void Main()

{

Point[] points = new Point[] {new Point(3, 3), new Point(1, 2)};

//下面是对Point的IComparable<T> CompareTo方法的调用

if(points[0].CompareTo(points[1]) > 0)

{

Point tempPoint = points[0];

points[0] = points[1];

points[1] = tempPoint;

}

Console.WriteLine("Points from closest to (0,0) farther");

foreach(Point p in points)

{

Console.WriteLine(p);

}

}

}

C#编译器要求将实现了接口的方法标记为public。CLR要求将接口方法标记为virtual.如果不在源代码中将接口方法显示标记为virtual,

编译器会把它们标记为virtual和sealed,这会阻止派生类重写接口方法。如果将方法显示标记为virtual,编译器会把方法标记为virtual(保留为unsealed),

这样一来,派生类就可以重写接口方法。

如果接口方法为sealed, 派生类就不能重写这个方法。不过,派生类可以重新继承同一个接口,

并可以为该接口的方法提供自己的实现。在一个对象上调用一个接口的方法时,将调用与这个对象的类型关联的实现。

例子:

using System;

public static class Program

{

public static void Mina()

{

//第一个例子

Base b = new Base();

//用b的类型来调用Dispose:"Base's Dispose"

((IDisposable)b).Dispose();

//第二个例子

Derived d = new Derived();

//对d的类型来调用Dispose:"Derived's Dispose"

d.Dispose();

//用d的对象类型来调用Dispose:"Derived's Dispose"

((IDisposable)d).Dispose();

//第三个例子

b = new Derived();

//用b的类型来调用Dispose:"Base's Dispose"

b.Dispose();

//用b的对象的类型来调用Dispose:"Derived Dispose"

((IDisposable)b).Dispose();

}

}

//这个类派生自Object,而且它实现了IDisposable接口

internal class Base : IDisposable

{

//这个方法隐式标记为sealed, 不能被重写

public void Dispose()

{

Console.WriteLine("Base's Dispose");

}

}

//这个类派生自Base,而且他重新实现了IDisposable

internal class Derived : Base, IDisposable

{

//这个方法不能从写Base 的 Dispose方法

//'new' 用于表明该方法重新实现了IDisposable的Dispose方法

new public void Dispose()

{

Console.WriteLine("Derived's dispose");

//注意,下面这行代码展示了如何调用一个基类的实现(如果需要的话)

//Base.Dispose();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: