繁体   English   中英

c#中“base”关键字的真正目的是什么?

[英]What really is the purpose of “base” keyword in c#?

因此,对于在我的应用程序的每个页面中使用的一些常见可重用方法的基类......

public class BaseClass:System.Web.UI.Page
{
   public string GetRandomPasswordUsingGUID(int length)
   {
      string guidResult = System.Guid.NewGuid().ToString();
      guidResult = guidResult.Replace("-", string.Empty);
      return guidResult.Substring(0, length);
   }
}

所以如果我想使用这种方法,我会这样做,

public partial class forms_age_group : BaseClass
{
      protected void Page_Load(object sender, EventArgs e)
      {
            //i would just call it like this
            string pass = GetRandomPasswordUsingGUID(10);
      }
}

它做了我想要的,但是有一个“Base”关键字处理 c# 中的基类......我真的想知道什么时候应该在我的派生类中使用 base 关键字......

有什么好的例子...

base关键字用于在链接构造函数时或当您想要访问基类中已被覆盖或隐藏在当前类中的成员(方法、属性、任何内容)时引用基类。 例如,

class A {
    protected virtual void Foo() {
        Console.WriteLine("I'm A");
    }
}

class B : A {
    protected override void Foo() {
        Console.WriteLine("I'm B");
    }

    public void Bar() {
        Foo();
        base.Foo();
    }
}

有了这些定义,

new B().Bar();

会输出

I'm B
I'm A

当您override功能但仍希望覆盖的功能也发生时,您将使用base关键字。

例子:

 public class Car
 {
     public virtual bool DetectHit() 
     { 
         detect if car bumped
         if bumped then activate airbag 
     }
 }


 public class SmartCar : Car
 {
     public override bool DetectHit()
     {
         bool isHit = base.DetectHit();

         if (isHit) { send sms and gps location to family and rescuer }

         // so the deriver of this smart car 
         // can still get the hit detection information
         return isHit; 
     }
 }


 public sealed class SafeCar : SmartCar
 {
     public override bool DetectHit()
     {
         bool isHit = base.DetectHit();

         if (isHit) { stop the engine }

         return isHit;
     }
 }

如果你在一个类和它的基类中有相同的成员,那么调用基类成员的唯一方法是 using base关键字:

protected override void OnRender(EventArgs e)
{
   // do something

   base.OnRender(e);

   // just OnRender(e); will cause StakOverFlowException
   // because it's equal to this.OnRender(e);
}

base关键字用于访问基类中已被子类中的成员覆盖(或隐藏)的成员。

例如:

public class Foo
{
    public virtual void Baz()
    {
        Console.WriteLine("Foo.Baz");
    }
}

public class Bar : Foo
{
    public override void Baz()
    {
        Console.WriteLine("Bar.Baz");
    }

    public override void Test()
    {
        base.Baz();
        Baz();
    }
}

然后调用Bar.Test会输出:

Foo.Baz;
Bar.Baz;

c#中“base”关键字的真正用途如下:假设你只想调用父类的参数化构造函数——那么你可以使用base并传递参数,请看下面的例子...

例子 -

 class Clsparent
{
    public Clsparent()
    {
        Console.WriteLine("This is Clsparent class constructor");
    }
    public Clsparent(int a, int b)
    {
        Console.WriteLine("a value is=" + a + " , b value is=" + b);
    }
}
class Clschild : Clsparent
{
    public Clschild() : base(3, 4)
    {
        Console.WriteLine("This is Clschild class constructor");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Clschild objclschild = new Clschild();
        Console.Read();
    }
}

Base 有两种使用方式。

  1. 带功能的底座
  2. 带变量的基础。

带功能的底座

当 base 与函数一起使用时,它的目的是在子类继承父类时使用参数调用父类。 我会用一个例子来解释。

  1. 在以下示例中,控制台打印..

参数为1,这是子构造函数

  1. 现在,如果您删除了 base(parameter),则控制台会打印..

这是父构造函数,这是子构造函数

当您从子类实例化对象时,构造函数会在实例化后立即调用。 当您从子类继承父类时,父类和子类中的构造函数都会被调用,因为两者都是实例化的。 使用 base() 时,您直接调用父类中的构造函数。 所以如果说base(),则表示父类中的构造函数不带参数,使用base(parameter)时,表示父类中的构造函数带参数。 这是一种函数重载。 base() 括号内使用的参数变量的类型由与 base 一起使用的函数的参数列表定义(在以下实例中它是 child(int parameter))

using System;

class Parent
{
    public Parent()
    {
        Console.WriteLine("This is Parent Constructor");
    }
    public Parent(int parameter)
    {
        Console.WriteLine("parameter is " + parameter);
    }
}

class Child : Parent
{
    public Child(int parameter): base(parameter)
    {
        Console.WriteLine("This is child constructor");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Child childObject = new Child(1);
    }
}

演示https://repl.it/@donqq/baseKeyword#main.cs


带变量的基础。

  1. 在以下示例中,控制台打印..

父母,孩子。

在下面的例子中,如果使用 base 关键字,则表示您寻址到子类继承的父类。 如果你使用它,你就寻址到类本身,这意味着当你实例化子类时子类,从而调用它的构造函数。 因此,当您使用 base.value 时,它​​意味着您引用了父类中的变量,而当您引用 this.value 时,它​​意味着您引用了子类中的变量。 当两者具有相同名称时,您可以区分使用此基数和 this 关键字引用的变量。 请记住,您不能在函数外部的类中使用 base, this 关键字。 您必须在函数内部使用它们来引用在全局级别初始化的变量。 此外,您不能使用它们来引用在函数内部初始化的局部变量。

using System;

class Parent
{
    public string value = "Parent";
}

class Child : Parent
{
    public string value = "Child";

    public Child() {
      Console.WriteLine(base.value);
      Console.WriteLine(this.value);
    }

}

class Program
{
    static void Main(string[] args)
    {
        Child childObject = new Child();
    }
}

演示https://repl.it/@donqq/Base-Class

当您覆盖派生类中的方法但只想在原始功能之上添加附加功能时使用 Base

例如:

  // Calling the Area base method:
  public override void Foo() 
  {
     base.Foo(); //Executes the code in the base class

     RunAdditionalProcess(); //Executes additional code
  }

您可以使用 base 来填充对象基类的构造函数中的值。

例子:

public class Class1
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }

    public Class1(int id, string name, DateTime birthday)
    {
        ID = id;
        Name = name;
        Birthday = birthday;
    }
}

public class Class2 : Class1
{
    public string Building { get; set; }
    public int SpotNumber { get; set; }
    public Class2(string building, int spotNumber, int id, 
        string name, DateTime birthday) : base(id, name, birthday)
    {
        Building = building;
        SpotNumber = spotNumber;
    }
}

public class Class3
{
    public Class3()
    {
        Class2 c = new Class2("Main", 2, 1090, "Mike Jones", DateTime.Today);
    }
}

一般我们使用基类来重用基类的子类中的属性或方法,所以我们不需要在子类中再次重复相同的属性和方法。

现在,我们使用base关键字直接从基类调用构造函数或方法。

例子

public override void ParentMethod() 
  {
     base.ParentMethod(); //call the parent method

     //Next code.
  }

2) 例子

class child: parent
{
    public child() : base(3, 4) //if you have parameterised constructor in base class
    {

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM