C#继承示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProgramCall { class BaseClass { //Method to find Mul of Two numbers public int FindMul(int x, int y) { return (x * y); } //method to print given 2 numbers //When declared protected , can be accessed only from inside the derived class //cannot access with the instance of derived class protected void Print(int x, int y) { Console.WriteLine("First Number: " + x); Console.WriteLine("Second Number: " + y); } } class Derivedclass : BaseClass { public void Print3numbers(int x, int y, int z) { Print(x, y); //We can directly call baseclass members Console.WriteLine("Third Number: " + z); } } class MainClass { static void Main(string[] args) { //为派生类创建实例,以便基类成员 //这是可行的,因为派生类Derivedclass继承自基类 Derivedclass of = new Derivedclass(); of.Print3numbers(3,5,7); //调用内部基类的方法 int Mul = of.FindMul(3,5); //使用派生类实例调用基类方法 Console.WriteLine("Mul : " + Mul); Console.Read(); } } }
继承是面向对象编程的重要概念之一。
继承是我们可以将基类的属性或者方法继承到派生类中的过程。
在声明类和基类时,通过在派生类之后放置冒号来完成:
例如:
public class A (base class) { public A() { } } public class B : A (derived class : base class) { public B() { } }
C#继承语法
[Access Modifier] class ClassName : baseclassname { }
日期:2020-04-11 23:03:41 来源:oir作者:oir