Abstract Class 和 Interface用法

来源:互联网 发布:软考程序员科目有哪些 编辑:程序博客网 时间:2024/05/22 17:02

abstract 修饰符可以和类、方法、属性、索引器及事件一起使用。在类声明中使用 abstract 修饰符以指示某个类只能是其他类的基类。标记为抽象或包含在抽象类中的成员必须通过从抽象类派生的类来实现。


在此例中,类 Square 必须提供 Area 的实现,因为它派生自 ShapesClass:


abstract class ShapesClass
{
    abstract public int Area();
}
class Square : ShapesClass
{
    int x, y;
    // 如果基类没有提供一个Area() 方法 就编译出错
    public override int Area()
    {
        return x * y;
    }
}


接口:只包含方法、委托或事件的签名。方法的实现是在实现接口的类中完成的,如下面的示例所示:

interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // 执行中接口中方法 : 
    void ISampleInterface.SampleMethod()
    {
        // 实施方法;
    }

    static void Main()
    {
        //声明接口的实例
        ISampleInterface obj = new ImplementationClass();

        // 访问方法
        obj.SampleMethod();
    }
}

0 0