8.7.11 Inheritance

博客主要介绍了C#中类的相关知识。类支持单继承,object是所有类的最终基类。方法、属性和索引器可以是虚拟的,其实现可在派生类中重写。还介绍了抽象类,它可指定抽象成员,非抽象派生类必须实现这些成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Classes support single inheritance, and the type object is the ultimate base
class for all classes.
The classes shown in earlier examples all implicitly derive from object.
The example
using System;
class A
{
public void F() { Console.WriteLine("A.F"); }
}
shows a class A that implicitly derives from object. The example
class B: A
{
public void G() { Console.WriteLine("B.G"); }
}
class Test
{
static void Main() {
B b = new B();
b.F(); // Inherited from A
b.G(); // Introduced in B
Chapter 8 Language Overview
41
A a = b; // Treat a B as an A
a.F();
}
}
shows a class B that derives from A. The class B inherits A.s F method, and
introduces a G method of its own.
Methods, properties, and indexers can be virtual, which means that their
implementation can be overridden
in derived classes. The example
using System;
class A
{
public virtual void F() { Console.WriteLine("A.F"); }
}
class B: A
{
public override void F() {
base.F();
Console.WriteLine("B.F");
}
}
class Test
{
static void Main() {
B b = new B();
b.F();
A a = b;
a.F();
}
}
shows a class A with a virtual method F, and a class B that overrides F.
The overriding method in B contains
a call, base.F(), which calls the overridden method in A.
A class can indicate that it is incomplete, and is intended only as a base
class for other classes, by including
the modifier abstract. Such a class is called an abstract class. An
abstract class can specify abstract
members.members that a non-abstract derived class must implement. The
example
using System;
abstract class A
{
public abstract void F();
}
class B: A
{
public override void F() { Console.WriteLine("B.F"); }
}
class Test
{
static void Main() {
B b = new B();
b.F();
A a = b;
a.F();
}
}
introduces an abstract method F in the abstract class A. The non-abstract
class B provides an implementation
for this method.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值