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();
      }
    }
  }
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3