栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#基础语法:Base关键字学习笔记

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#基础语法:Base关键字学习笔记

它与this关键字一样,都是作为类的实例(因此不能调用基类的静态成员和抽象成员)简写或者替代而存在的,只不过this关键字用于替代本类的实例,base关键字用于替代基类的实例,用法很简单,其访问基类的形式如下: 

base.【标识符】

base[【表达式列表】]      这个类型的一看便可以大概猜测多用于基类实例的索引器操作,在我下面演示的代码中你会看到它的用法。

对于  base.【标识符】的访问形式再次说明一下:

对于非虚方法,这种访问仅仅是对基类实例成员的直接访问,完全等价于((base)this).【标识符】。

对于虚方法,对于这种访子类重写该虚方法运用这种访问形式也是(禁用了虚方法调用的机制)对基类实例成员的直接访问,将其看做非虚方法处理,此时则不等价于((base)this).【标识符】,因为这种格式完全遵守虚方法调用的机制,其声明试时为积累类型,运行时为子类类型,所以执行的还是子类的重写方法。于未重写的虚方法等同于简单的非虚方法处理。

测试代码如下:

using System;

namespace baseTest
{
  class father
  {
    string str1 = "this field[1] of baseclass", str2 = "this field[2] of baseclass";
    public void F1() //Non-virtual method
    {
      Console.WriteLine(" F1 of the baseclass");
    }
    public virtual void F2()//virtual method
    {
      Console.WriteLine(" F2 of the baseclass");
    }
    public virtual void F3()
    {
      Console.WriteLine(" F3 of the baseclass that is not overrided "); 
    }
    public string this[int index]
    {
      set
      {
 if (index==1 )
 {
   str1 = value;
 }
 else
 {
   str2 = value;
 }
      }
      get
      {
 if (index ==1)
 {
   return str1;
 }
 else
 {
   return str2;
 }
      }
    }
  }
  class Child:father
  {
    public void G()
    {
      Console.WriteLine("======Non-virtual methods Test =========");
      base.F1();
      ((father)this).F1();
      Console.WriteLine("======virtual methods Test=========");
      base.F2();
      ((father)this).F2();
      base.F3();
      ((father)this).F3();
      Console.WriteLine("=====Test the type that the tbase [[expression]] ==========");
      Console.WriteLine(base[1]);
      base[1] = "override the default ";
      Console.WriteLine(base[1]);
      Console.WriteLine("================Test Over=====================");
    }
    public override void F2()
    {
      Console.WriteLine(" F2 of the subclass ");
    }
    
    static void Main(string[] args)
    {
      Child child=new Child();
      child.G();
      Console.ReadKey();
    }
  }
}


base用于构造函数声明,用法和this用于构造函数声明完全一致,但base是对基类构造函数形参的匹配。

 

using System;

namespace baseCoTest
{
  class base
  {
    public base(int a, string str)
    {
      Console.WriteLine("base. base(int a,string str)");
    }
    public base(int a)
    {
      Console.WriteLine("base. base(int a)");
    }
    public base()
    {
    }
  }
  class Sub : base
  {
    public Sub()
    {
    }
    public Sub(int a)
      : base(1, "123")
    {
      Console.WriteLine("Sub .Sub(int a)");
    }
    class Test
    {
      public static void Main()
      {
 Sub sub = new Sub(1);
 Console.ReadKey();
      }
    }
  }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/125047.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号