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

后端 未结 9 1134
误落风尘
误落风尘 2020-12-08 00:42

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 Get         


        
相关标签:
9条回答
  • 2020-12-08 01:06

    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

    For example:

      // Calling the Area base method:
      public override void Foo() 
      {
         base.Foo(); //Executes the code in the base class
    
         RunAdditionalProcess(); //Executes additional code
      }
    
    0 讨论(0)
  • 2020-12-08 01:09

    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. 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
    
    0 讨论(0)
  • 2020-12-08 01:10

    You can use base to fill values in the constructor of an object's base class.

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题