C# 中的接口和继承
csharpprogrammingserver side programming更新于 2025/7/13 6:22:17
接口
接口被定义为一种语法契约,所有继承该接口的类都应遵循该契约。接口定义了语法契约的"什么"部分,而派生类定义了语法契约的"如何"部分。
让我们看一个 C# 中接口的示例。
示例
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication {
public interface ITransactions {
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions {
private string tCode;
private string date;
private double amount;
public Transaction() {
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a) {
tCode = c;
date = d;
amount = a;
}
public double getAmount() {
return amount;
}
public void showTransaction() {
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester {
static void Main(string[] args) {
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}
输出
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
继承
继承允许我们根据一个类来定义另一个类,这使得应用程序的创建和维护更加容易。这也提供了重用代码功能的机会,并加快了实现速度。
继承的理念实现了"是-是"关系。例如,哺乳动物是动物,狗是哺乳动物,因此狗也是动物,等等。
以下示例展示了如何在 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 RectangleTester {
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
相关文章
C# 程序实现 FizzBuzz
C# 中的算术运算符是什么?
C# 中的耦合
理解 C# 中的 IndexOutOfRangeException 异常
理解 C# 中的数组 IndexOutofBoundsException
C# 程序一次性读取文件的所有行
C# 值元组
在 C# 中递归列出文件
在 C# 中获取文件中的字节数
C# 程序获取驱动器中的可用空间
打印
下一节 ❯❮ 上一节