簡體   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