溫馨提示×

abstract c# 在接口中如何應用

c#
小樊
89
2024-07-18 19:56:24
欄目: 編程語言

在C#中,可以在接口中定義抽象方法來強制實現類實現特定的行為。接口中的方法沒有方法體,只有方法聲明。當類實現一個接口時,它必須實現接口中定義的所有抽象方法。

以下是一個簡單的示例,演示如何在接口中定義抽象方法:

interface IShape
{
    void Draw();
}

class Circle : IShape
{
    public void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}

class Rectangle : IShape
{
    public void Draw()
    {
        Console.WriteLine("Drawing a rectangle");
    }
}

class Program
{
    static void Main()
    {
        IShape circle = new Circle();
        circle.Draw(); // Output: Drawing a circle

        IShape rectangle = new Rectangle();
        rectangle.Draw(); // Output: Drawing a rectangle
    }
}

在上面的示例中,接口IShape定義了一個抽象方法Draw()。類CircleRectangle都實現了IShape接口,并且分別實現了Draw()方法。在Main()方法中,可以創建CircleRectangle對象,并調用Draw()方法來觸發相應的繪制操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女