zoukankan      html  css  js  c++  java
  • Base和this关键字

      今天看公司程序的一个类,其构造函数中含有base关键字且有参数,不知道什么意思,就上网查了查学习一下,并在这里写下总结。

      Base关键字,主要是应用于类的继承,可以在子类的构造函数、方法、属性实例属性中引用父类中的公有(public)有以及受保护(protected)的 方法、字段、属性、索引器等。

      this关键字,主要是引用当前实例或者继承的方法。

     1 public class A
     2     {
     3         public A(string str,int t)
     4         {
     5             A.str = str;
     6             A.t = t;
     7         }
     8         private static string str;
     9         private static int t;
    10         public void Func(int t)
    11         {
    12             Console.WriteLine(this.ToString()+ "Func t:", t);
    13         }
    14         public string PropertyA 
    15         {
    16             get 
    17             {
    18                 return A.str;
    19             } 
    20         } 
    21         protected void FuncA(string s)
    22         {
    23             Console.WriteLine(this.ToString() + "FuncA s:", s);
    24         }
    25     }
    26     public class A_1 : A
    27     {
    28         public A_1(int t)
    29             : base(str,t)
    30         {
    31             A_1.t = t;
    32         }
    33         private static string str;
    34         private static int t;
    35         private void Init()
    36         {
    37             str = base.PropertyA;
    38         }
    39         public void FuncA(string s) //重载基类方法
    40         {
    41             Console.WriteLine(this.ToString() + "FuncA s:", s);
    42         }
    43     }
    44     public class A_1_1 : A_1
    45     {
    46         public A_1_1()
    47             : base(t)
    48         { 
    49         }
    50         private static int t;
    51         public void Func()
    52         {
    53             base.FuncA(this.ToString() + base.PropertyA);//此处引用的是A_1的方法FuncA
    54         }
    55     }

    对于多层继承的情况:

      若存在重载:base指向直接继承的父类的重载的方法、字段等;即 Line 53

      若不存在重载:base指向任意层父类的方法、字段等。即 Line 53 base.PropertyA

      注:类的实例化顺序

      一般从基类开始依次进行,即此处:A --> A_1 --> A_1_1。所以类的实例化都是从System.Object开始,即System.Object.Object()。

      

  • 相关阅读:
    创建react项目
    解决移动端弹窗下页面滚动问题
    前端常用的几种加密方式
    http请求状态码
    vue代理配置
    自动化测试实操案例详解 | Windows应用篇
    Google 再见 Java
    一次诡异的 SQL 数量统计查询不准的问题
    Maven
    淘宝技术分享:手淘亿级移动端接入层网关的技术演进之路
  • 原文地址:https://www.cnblogs.com/forevertime/p/5105514.html
Copyright © 2011-2022 走看看