如何在 C# 中继承类?
继承允许我们基于另一个类来定义类,这使创建和维护应用程序更容易。
在创建类时,编程员无需编写全新的数据成员和成员函数,他可以指定新类应该继承现有类成员。此现有类称为基类,新类称为派生类。一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口中继承数据和函数。
以下是一个示例:-
示例
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;
}
// Derived class
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class Demo {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}输出
Total area: 35
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP