C#继承
来源:互联网 发布:python程序员怎么样? 编辑:程序博客网 时间:2024/06/01 07:44
C#继承
①构造函数
构造函数是在创建给定类型的对象时执行的类方法。构造函数具有与类相同的名称,它通常初始化新对象的数据成员。
public class Taxi{ public bool isInitialized; public Taxi() { isInitialized = true; }}class TestTaxi{ static void Main() { Taxi t = new Taxi(); System.Console.WriteLine(t.isInitialized); }}
②base
构造函数可以使用 base 关键字来调用基类的构造函数。
public class Manager : Employee{ public Manager(int annualSalary) : base(annualSalary) { //Add further instructions here. }}
在此示例中,基类的构造函数在执行构造函数块之前被调用。base 关键字可带参数使用,也可不带参数使用。构造函数的任何参数都可用作 base 的参数,或用作表达式的一部分。
在派生类中,如果不使用 base 关键字来显式调用基类构造函数,则将隐式调用默认构造函数(如果有的话)。
base 关键字用于从派生类中访问基类的成员:
1、调用基类上已被其他方法重写的方法。
2、指定创建派生类实例时应调用的基类构造函数。
1、调用基类上已被其他方法重写的方法。
2、指定创建派生类实例时应调用的基类构造函数。
基类访问只能在构造函数、实例方法或实例属性访问器中进行。从静态方法中使用 base 关键字是错误的。
在本例中,基类 Person 和派生类 Employee 都有一个名为 Getinfo 的方法。通过使用 base 关键字,可以从派生类中调用基类的 Getinfo 方法。
// keywords_base.cs// Accessing base class membersusing System;public class Person{ protected string ssn = "444-55-6666"; protected string name = "John L. Malgraine"; public virtual void GetInfo() { Console.WriteLine("Name: {0}", name); Console.WriteLine("SSN: {0}", ssn); }}class Employee : Person{ public string id = "ABC567EFG"; public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); Console.WriteLine("Employee ID: {0}", id); }}class TestClass{ static void Main() { Employee E = new Employee(); E.GetInfo(); }}
// keywords_base2.csusing System;public class BaseClass{ int num; public BaseClass() { Console.WriteLine("in BaseClass()"); } public BaseClass(int i) { num = i; Console.WriteLine("in BaseClass(int i)"); } public int GetNum() { return num; }}public class DerivedClass : BaseClass{ // This constructor will call BaseClass.BaseClass() public DerivedClass() : base() { } // This constructor will call BaseClass.BaseClass(int i) public DerivedClass(int i) : base(i) { } static void Main() { DerivedClass md = new DerivedClass(); DerivedClass md1 = new DerivedClass(1); }}
输出:
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
SSN: 444-55-6666
Employee ID: ABC567EFG
0 0
- C# 继承
- C#继承
- C# 继承
- C# 继承
- c# 继承
- C# 继承
- C#继承
- C# 继承
- C# 继承
- C# 继承
- C# 继承
- C#继承
- c#继承
- C# 继承
- C#继承
- C# 继承
- C# 继承
- C# 继承
- leetcode[20]:Valid Parentheses
- UITableViewQQ列表效果
- Android使用HttpClient实现文件上传到PHP服务器,并监控进度条
- 图文介绍MyEclipse (2015) 中创建简单的Maven项目的步骤(用于生成可执行jar文件)
- binbinyang---百度地图androidAPI Android SDK v3.5.0-------------1.Hello BaiduMap
- C#继承
- 带模除法
- read/write函数
- openwrt 修改默认 IP
- Leetcode 239 Sliding Window Maximum
- Apache 跨域配置
- 青城山之旅
- Eclipse:显示堆内存状态
- JSP实现邮件发送机制