zoukankan      html  css  js  c++  java
  • C#在派生类中调用基类成员

    一、在派生类中调用基类成员

    在C#的派生类中,我们可以使用base关键字调用基类中的公有或者受保护成员。这些成员只能是构造函数、实例方法或者实例属性。

    base关键字调用基类成员的语法格式如下:

    base . identifier或

    base[expression-list]注意:

    ?base关键字不能用在派生类的静态方法中。

    ?必须显式添加基类的构造函数。

    二、示例
      
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace Test
    {
        class Program
        {
            public class A                     // 基类
            {
                protected string name; // 受保护字段成员,可在当前类和派生类中访问
                protected int age;             // 受保护字段成员
                public A(string name, int age) // 实例构造函数
                {
                    this.name = name;
                    this.age = age;
                }
                public void Show()             // 公共方法
                {
                    Console.WriteLine("基类-name:{0} age:{1}",name,age);
                }
            }
            public class B : A                 // 这是派生类,以A作为基类
            {
                private int ID;                // 派生类的成员
                public B(int ID, string name, int age)
                    : base(name, age)          // 调用直接基类的实例构造函数
                {
                    this.ID = ID;
                    Console.WriteLine("派生类B的构造函数");
                }
                new public void Show() // 用new关键字隐藏基类中的同名方法
                {
                    Console.WriteLine("ID:{0}", ID);
                    Console.WriteLine("派生类B的Show方法");
                    base.Show();               // 调用基类的方法
                }
            }
            static void Main(string[] args)
            {
                // C#在派生类中调用基类成员-www.baike369.com
                B b = new B(100,"BaiXue",18);  // 创建类的实例
                b.Show();                      // 调用派生类B的方法
                Console.ReadLine();
            }
        }
    }

    运行结果:
     
    派生类B的构造函数
    ID:100
    派生类B的Show方法
    基类-name:BaiXue age:18

  • 相关阅读:
    笔记-归并排序
    Repeated Substring Pattern
    Assign Cookies
    Number of Boomerangs
    Paint Fence
    Path Sum III
    Valid Word Square
    Sum of Two Integers
    Find All Numbers Disappeared in an Array
    First Unique Character in a String
  • 原文地址:https://www.cnblogs.com/melao2006/p/4239253.html
Copyright © 2011-2022 走看看