【问题标题】:What really is the purpose of "base" keyword in c#?c# 中“base”关键字的真正目的是什么?
【发布时间】:2011-02-08 07:33:39
【问题描述】:

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

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 关键字......

任何好的例子...

【问题讨论】:

    标签: c# keyword base


    【解决方案1】:

    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
    

    【讨论】:

    • 不限于功能。无论类(父类和子类)有歧义,base 关键字都会明确用户正在谈论的方法/数据成员。
    • A.Foo() 会和base.Foo() 做同样的事情吗?
    • @KyleDelaney 不,A.Foo() 是一个静态方法调用。由于 A.Foo() 不是静态的,如果你这样做,你会得到一个错误。
    • 您也可以在被覆盖的方法中添加base.Foo(); 来调用它。
    【解决方案2】:

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

    【讨论】:

    • +1 for if(isHit) {删除 i 并且它具有完全不同的含义} ;)
    • @andrewWinn:这可能是 C# 语言设计者无法将 VB.NET 的 IsNot 关键字引入 C# 语言的主要原因。它会有鼻屎的外观:-D 呵呵
    【解决方案3】:

    如果您在一个类及其基类中有相同的成员,那么调用基类成员的唯一方法是使用 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);
    }
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        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;
        

        【讨论】:

          【解决方案6】:

          Base 有两种使用方式。

          1. 带有函数的基础
          2. 带有变量的基础。

          基础功能

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

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

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

          1. 现在,如果您删除了基础(参数),那么控制台会打印......

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

          当您从子类实例化一个对象时,构造函数会在它被实例化后立即被调用。当你从子类继承父类时,父类和子类中的构造函数都会被调用,因为它们都被实例化了。使用 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 时,则表示您引用了子类中的变量。您可以区分您使用此基数引用的变量,当两者具有相同名称时,此关键字。请记住,您不能在函数之外的类中使用 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

          【讨论】:

            【解决方案7】:

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

            例如:

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

            【讨论】:

              【解决方案8】:

              您可以使用 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);
                  }
              }
              

              【讨论】:

                【解决方案9】:

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

                现在,我们使用 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
                    {
                
                    }
                }
                

                【讨论】:

                  猜你喜欢
                  • 2019-07-05
                  • 2011-09-09
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-02-08
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-12-17
                  • 1970-01-01
                  相关资源
                  最近更新 更多