简体   繁体   English

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

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

Thus for used base class for some commom reusable methods in every page of my application...因此,对于在我的应用程序的每个页面中使用的一些常见可重用方法的基类......

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

So if i want to use this method i would just do,所以如果我想使用这种方法,我会这样做,

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

It does what i want but there is a "Base" keyword that deals with base class in c# ... I really want to know when should use base keyword in my derived class....它做了我想要的,但是有一个“Base”关键字处理 c# 中的基类......我真的想知道什么时候应该在我的派生类中使用 base 关键字......

Any good example...有什么好的例子...

The base keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) in the base class that has been overridden or hidden in the current class. base关键字用于在链接构造函数时或当您想要访问基类中已被覆盖或隐藏在当前类中的成员(方法、属性、任何内容)时引用基类。 For example,例如,

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

With these definitions,有了这些定义,

new B().Bar();

would output会输出

I'm B
I'm A

You will use base keyword when you override a functionality but still want the overridden functionality to occur also.当您override功能但仍希望覆盖的功能也发生时,您将使用base关键字。

example:例子:

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

If you have the same member in a class and its base class then the only way to call a member of the base class is the using base keyword:如果你在一个类和它的基类中有相同的成员,那么调用基类成员的唯一方法是 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);
}

The base keyword is used to access members in the base class that have been overridden (or hidden) by members in the subclass. base关键字用于访问基类中已被子类中的成员覆盖(或隐藏)的成员。

For example:例如:

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

Calling Bar.Test would then output:然后调用Bar.Test会输出:

Foo.Baz;
Bar.Baz;

The real purpose of the “base” keyword in c# is as follows: suppose you want to call only the parent class' parameterized constructor - then you can use base and pass the parameters, please see below example... c#中“base”关键字的真正用途如下:假设你只想调用父类的参数化构造函数——那么你可以使用base并传递参数,请看下面的例子...

Example -例子 -

 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 is used in two ways. Base 有两种使用方式。

  1. Base with functions带功能的底座
  2. Base with variables.带变量的基础。

Base with functions带功能的底座

When base is used with functions the purpose of it is to call the parent class with parameters when parent class is inherited by the child class.当 base 与函数一起使用时,它的目的是在子类继承父类时使用参数调用父类。 I will explain that with an example.我会用一个例子来解释。

  1. In the following example console prints..在以下示例中,控制台打印..

parameter is 1, This is child constructor参数为1,这是子构造函数

  1. Now if you removed base(parameter), then console prints..现在,如果您删除了 base(parameter),则控制台会打印..

This is Parent Constructor, This is child constructor这是父构造函数,这是子构造函数

When you instantiate an object from child class, the constructor is called as soon as it's instantiated.当您从子类实例化对象时,构造函数会在实例化后立即调用。 When you inherit the parent class from child class, both constructors in parent, and child classes are called because both are instantiated.当您从子类继承父类时,父类和子类中的构造函数都会被调用,因为两者都是实例化的。 When using base() you directly call the constructor in the parent class.使用 base() 时,您直接调用父类中的构造函数。 So if it says base(), it means the constructor in parent class without any parameters, when using base(parameter), it means the constructor in the parent class with a parameter.所以如果说base(),则表示父类中的构造函数不带参数,使用base(parameter)时,表示父类中的构造函数带参数。 This is a sort of function overloading.这是一种函数重载。 The type of parameter variable used inside of the base() brackets is defined by parameters list of the function used with base (in the following instance it's child(int 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);
    }
}

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


Base with variables.带变量的基础。

  1. In the following example, console prints..在以下示例中,控制台打印..

Parent, Child.父母,孩子。

In the following example, if you use base keyword, it means you address to the parent class inherited by the child class.在下面的例子中,如果使用 base 关键字,则表示您寻址到子类继承的父类。 If you use this, you address to the class itself, which means the child class as you instantiated the child class, and thereby calling its constructor.如果你使用它,你就寻址到类本身,这意味着当你实例化子类时子类,从而调用它的构造函数。 So when you use base.value it means you refer to the variable in the parent class, and when you refer to the this.value it means you refer to the variable in the child class.因此,当您使用 base.value 时,它​​意味着您引用了父类中的变量,而当您引用 this.value 时,它​​意味着您引用了子类中的变量。 You can distinguish to which variable you refer to with this base, this keywords when both have same names.当两者具有相同名称时,您可以区分使用此基数和 this 关键字引用的变量。 remember you can't use base, this keywords in the class outside of a function.请记住,您不能在函数外部的类中使用 base, this 关键字。 You have to use them inside of a function to refer to a variable initialised in the global level.您必须在函数内部使用它们来引用在全局级别初始化的变量。 Also you can't use them to refer to a local variable initialised inside of a function.此外,您不能使用它们来引用在函数内部初始化的局部变量。

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

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

Base is used when you override a method in a derived class but just want to add additional functionality on top of the original functionality当您覆盖派生类中的方法但只想在原始功能之上添加附加功能时使用 Base

For example:例如:

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

     RunAdditionalProcess(); //Executes additional code
  }

You can use base to fill values in the constructor of an object's base class.您可以使用 base 来填充对象基类的构造函数中的值。

Example:例子:

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

Generally, we are using the base class to reuse the property or methods in child class of the base class, so we no need to repeat the same property and methods again in the child class.一般我们使用基类来重用基类的子类中的属性或方法,所以我们不需要在子类中再次重复相同的属性和方法。

Now, we use the base keyword to call a constructor or method from base class directly.现在,我们使用base关键字直接从基类调用构造函数或方法。

Example例子

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

     //Next code.
  }

2) Example 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