Get the App
SLTechnology News&Howtos  ›  Development  › 

How to create derived classes in C #

Shulou Source: shulou.com Published: 2022-06-01 01:52:39 09月13日 Update

这篇文章主要讲解了"C#中怎么创建派生类",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"C#中怎么创建派生类"吧!

基类和派生类

一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。

C# 中创建派生类的语法如下:

class

{

...

}

class :

{

...

}

假设,有一个基类 Shape,它的派生类是 Rectangle:

using System;

namespace InheritanceApplication

{

class Shape

{

public void setWidth(int w)

{

width = w;

}

public void setHeight(int h)

{

height = h;

}

protected int width;

protected int height;

}

// 派生类

class Rectangle: Shape

{

public int getArea()

{

return (width * height);

}

}

class RectangleTester

{

static void Main(string[] args)

{

Rectangle Rect = new Rectangle();

Rect.setWidth(5);

Rect.setHeight(7);

// 打印对象的面积

Console.WriteLine("总面积: {0}", Rect.getArea());

Console.ReadKey();

}

}

}

当上面的代码被编译和执行时,它会产生下列结果:

总面积: 35感谢各位的阅读,以上就是"C#中怎么创建派生类"的内容了,经过本文的学习后,相信大家对C#中怎么创建派生类这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

Tags: Caching learning content multiple total area interface code function object that is ideas situation meaning data articles more knowledge knowledge points articles results Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia OPPO Reno Apple Linux Huawei