温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#多继承与类扩展的实践

发布时间:2024-07-17 09:40:06 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在C#中,不支持多继承,即一个类只能继承一个父类。但是可以通过接口实现多继承的效果。另外,可以使用类扩展的方式来为现有类添加新的功能,使得类具有多继承的特性。

下面是一个示例代码,演示了如何通过接口实现多继承和类扩展:

using System;

// 定义接口1
interface IShape
{
    double GetArea();
}

// 定义接口2
interface IColor
{
    void SetColor(string color);
}

// 定义父类
class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing shape...");
    }
}

// 定义子类,并实现多继承效果
class Circle : Shape, IShape, IColor
{
    private double radius;
    private string color;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public double GetArea()
    {
        return Math.PI * radius * radius;
    }

    public void SetColor(string color)
    {
        this.color = color;
    }

    public override void Draw()
    {
        Console.WriteLine($"Drawing circle with radius {radius} and color {color}...");
    }
}

// 类扩展:为Shape类添加一个新的方法
static class ShapeExtensions
{
    public static void DisplayInfo(this Shape shape)
    {
        Console.WriteLine("Displaying shape information...");
    }
}

class Program
{
    static void Main()
    {
        Circle circle = new Circle(5);
        circle.SetColor("Red");

        Console.WriteLine("Area of circle: " + circle.GetArea());
        circle.Draw();
        circle.DisplayInfo();
    }
}

在上述示例中,接口IShapeIColor分别定义了获取面积和设置颜色的方法。类Shape是父类,类Circle继承了Shape类并实现了IShapeIColor接口,从而实现了多继承的效果。同时,通过类扩展的方式为Shape类添加了一个新的方法DisplayInfo

Main方法中,创建了一个Circle对象,并调用了相关方法来获取面积、设置颜色、绘制图形以及显示额外信息。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI