C # Fundamentals (base, this, new, override, abstract, virtual, static)

Source: Internet
Author: User
Tags modifiers

Objective

This article mainly to explain in C #, I feel that the master is not good or not much, not too familiar with the keywords, mainly including base, this, new, override, abstract, Virtual and execution issues between the static field and the static constructor.

Base keyword

The base keyword is used to implement access to a base class public or protected member in a derived class, but only in constructors, instance methods, and instance property accessors:

    • Calls a method on the base class that has been overridden by another method.

    public class Father    {public         virtual void Say ()        {            Console.WriteLine ("Father Say");        }    }    public class Son:father    {public        override void Say ()        {            base. Say ();            Console.WriteLine ("Son Say");        }    }
    • Specifies the base class constructor that should be called when creating an instance of a derived class.

    public class Father    {public        string Name {get; set;}        Public Father ()        {            Name = "Father";        }    }    public class Son:father    {public        Son ()            : Base ()        {                     }    }

Using the base keyword from a static method is an error.

this keyword

It is used to reference the current instance of a class, and also includes inherited methods, which can often be hidden from this:

    • Qualify a member that is hidden by a similar name
    public class person    {public        string Name {get; set;}        public int Age {get; set;}        Public person (String Name, int.)        {this            . name = name;            This. Age = Age;        }    }
    • To pass an object as a parameter to another method
    public class person    {public        string Name {get; set;}        public int Age {get; set;}        Public person (String Name, int.)        {this            . name = name;            This. Age = Age;        }        public void calltest (person person)        {            Console.WriteLine (person). Name+person. age);        }        public void Call ()        {            calltest (this);        }    }
    • Declaring indexers
    public class person    {        string[] personlist = new STRING[10];        public string this[int param]        {            get {return personlist[param];}            set {Personlist[param] = value;}        }

New keyword

First, the new operator

1, new A class, new completes the following two aspects of the content: first, call the new Class command to allocate memory for the instance in the managed heap, and the other is to call the constructor to implement object initialization.

2. When a struct is new, the new operator is used to call its with constructor to complete the initialization of the instance.

3, new an int, the new operator is used to initialize its value to 0.

4, the new operator is not overloaded.

5, new allocates memory fails, throws an OutOfMemoryException exception.

Second, new modifier

new  keyword can explicitly hide members inherited from a base class.   When you hide an inherited member, the derived version of the member replaces the base class version.  new modifier, and the result is a warning. " > Although you can hide a member without using the  new  modifier, a warning is generated.  new to explicitly hide a member, it suppresses this warning and documents the fact that the derived ver Sion is intended as a replacement. " > If you make

When you explicitly hide a member with new, this warning is canceled and the fact that you want to replace it with a derived version is logged.

A method defined in a subclass with the same name as the parent class in the New keyword adornment is called overwrite. Overwriting does not change the functionality of the parent class method.

    public class A    {public        virtual void Test ()        {             Console.WriteLine ("A.test ()");         }    }    public class b:a    {public        new void Test ()        {             Console.WriteLine ("B.test ()");         }    }    Class program    {        static void Main (string[] args)        {            A A = new A ();            A.test ();            b b = new B ();            B.test ();            A C = new B ();            C.test ();            Console.ReadLine ();}}}    

When you create a parent class with a subclass, such as A C = new B (), overrides do not change the functionality of the parent class, and the parent class feature is still called. (different from override, explained below)

Third, new constraints

The new constraint specifies that any type parameter in a generic class declaration must have a public parameterless constructor. If you want to use the new constraint, the type cannot be an abstract type.

When used with other constraints, the new () constraint must be specified last:

    public class Classa<t>where t:icomparable, New ()    {        ////    }

Override keyword

To extend or modify an abstract implementation or virtual implementation of an inherited method, property, indexer, or event, you must use the override modifier.

The method overridden by the override declaration is called the overriding base method. The overridden base method must have the same signature as the override method.

You cannot override a non-virtual method or a static method. The overridden base method must be virtual,abstract, or override.

The method of virtual modification with the keyword is called the virtual method. You can declare a method with the same name in the subclass with Override, which is called "overriding." The corresponding method is not modified by virtual, we call it a real method. Rewriting alters the functionality of the parent class method.

    public class A    {public        virtual void Test ()        {             Console.WriteLine ("A.test ()");         }    }    public class b:a    {public        override void Test ()        {             Console.WriteLine ("B.test ()");         }    }    Class program    {        static void Main (string[] args)        {            A A = new A ();            A.test ();            b b = new B ();            B.test ();            A C = new B ();            C.test ();            Console.ReadLine ();        }    }

New and override

1, whether overridden or overwritten, does not affect the functionality of the parent class itself.

2, when creating a parent class with a subclass, such as A C = new B (), overrides change the function of the parent class, that is, the function of the child class is called, but overrides do not, still call the parent class function.

3, virtual methods, real methods can be overwritten (new), abstract methods, interfaces are not available.

4, abstract method, interface, the method marked as virtual can be rewritten (override), the real method can not.

5, rewrite the frequency of use is relatively high, to achieve polymorphism, the frequency of coverage is relatively low, used to inherit a class that could not be modified previously.

abstract keyword

The following five points are briefly summarized for the abstract keyword:

1. The class defined by the keyword abstract is an abstract class and can only be used as a base class and cannot be instantiated.
2. Classes defined in abstract do not necessarily contain abstract methods or can contain non-abstract methods.
The methods defined by 3.abstract must be included in the abstract class.
4. Abstract classes cannot be defined as sealed classes (sealed), abstract methods cannot use virtual, static, private modifiers
5. If a derived class does not implement all of the abstract methods, the derived class must also be declared as an abstract class.

Virtual keyword

Virtual method (virtual method)

The virtual keyword is used to decorate a method in a base class. There are two things you can do with virtual:

Scenario 1: The virtual method is defined in the base class, but the virtual method is not overridden in the derived class. In a call to a derived class instance, the virtual method uses the method defined by the base class.

Scenario 2: The virtual method is defined in the base class and then overridden in a derived class by using override. In a call to a derived class instance, the virtual method uses the derived overridden method.

Static fields and static constructors

Mainly to illustrate the order of execution:

1, the compiler at the time of compilation, the first analysis of the required static fields, if the static fields in which the class has a static constructor, then the initialization of the field will be ignored, if there is no static constructor, then the static field is initialized.

2. If there are more than one static class, the order of the initialized static members is initialized by the advanced rows referenced first, but if the initialization of the static members of the class depends on the static members of other classes, the dependent static members are initialized first.

3. Static fields of a class with static constructors are initialized only when referenced.

Let's take a look at two simple small examples:

    public class A    {public        static int X = b.y+1;        Static A () {}    } public    class B    {public        static int y=a.x+1;    }    Class program    {        static void Main (string[] args)        {            Console.WriteLine ("A.x={0},b.y={1}", A.x,b.y) ;            Console.ReadLine ();        }    }

How did it end? Let's look at a second small example:

    public class A    {public        static int X = b.y+1;    }    public class B    {public        static int y=a.x+1;        Static B () {}    }    class program    {        static void Main (string[] args)        {            Console.WriteLine ("A . X={0},b.y={1} ", a.x,b.y);            Console.ReadLine ();        }    }

In contrast, these two examples, if you want to match the results of your execution, it means that you should already understand the order in which they are executed.

Abstract, virtual, override, and new are the keywords of the four modifiers commonly used in the inheritance of a class, and are summarized here.

1. Commonly used Chinese name: Abstract abstraction method, virtual virtual method, override overriding base class method, new hidden base class method, override and new are sometimes called overriding base class methods.

2. Application: Abstract and virtual are used in the base class (parent class); Override and new are used in derived classes (subclasses).

3. Specific concepts:

Abstract abstraction method, is an empty method, there is no method body, the derived class must implement this method with override.

Virtual virtual method, this method must be declared as virtual if it is expected or expected that this method of the base class will be overridden in a future derived class (override or New).

Override overrides the Virtural method inherited from the base class, which can be understood as removing the old house, building a new house on the site, and no longer finding the old building (unless explicitly using base. Call the base class method).

New hides the virtual method that inherits from the base class, and the old house is still there, with the building next to it, to live in the apartment (called as a derived class object), to live in an old room (called as a base class object).

When a method with the same name as the base class appears in a derived class, and the method does not precede the override or the new modifier, the compiler reports a warning, but does not report an error, and the actual execution is equivalent to adding new.

4. The difference between abstract and virtual: The abstract method has not been implemented, and the base class can not be instantiated, except as a rule or symbol is not used; Virtual is better, derived classes want to rewrite the rewrite, do not want to rewrite to eat Lao Tzu. And the inheritance of good is also less use for the better, the less inheritance level, the more the more the new extension of the function of the less the better, virtual deep meaning.

5. The difference between override and new: When a derived class object is used as a base class type, override executes the base class method of the derived class method, new. If called as a derived class type, the override or new is executed.

Examples of the override and new differences are shown:


Define the base class
Class Car
{
public virtual void DescribeCar ()
{
System.Console.WriteLine ("Four wheels and an engine.");
}
}

Define the derived classes
Class Convertiblecar:car
{
Public new virtual void DescribeCar ()
{
Base. DescribeCar ();
System.Console.WriteLine ("A roof that opens up.");
}
}
Class Minivan:car
{
public override void DescribeCar ()
{
Base. DescribeCar ();
System.Console.WriteLine ("carries seven people.");
}
}
public static void TestCars1 ()
{
Car car1 = new car ();
Car1. DescribeCar ();
System.Console.WriteLine ("----------");

Convertiblecar car2 = new Convertiblecar ();
Car2. DescribeCar ();
System.Console.WriteLine ("----------");

Minivan Car3 = new minivan ();
Car3. DescribeCar ();

System.Console.WriteLine ("----------");

}

The output resembles the following:

Four wheels and an engine.

----------

Four wheels and an engine.

A roof that opens up.

----------

Four wheels and an engine.

Carries seven people.

----------

However, if we declare an array of objects derived from the Car base class. This array can store Car, Convertiblecar, and Minivan objects as follows:


public static void TestCars2 ()
{
Car[] cars = new CAR[3];
Cars[0] = new Car ();
CARS[1] = new Convertiblecar ();

CARS[2] = new minivan ();

}

Then use a foreach loop to access each Car object contained in the array and call the DescribeCar method, as follows:


foreach (Car vehicle in cars)
{
System.Console.WriteLine ("Car object:" + vehicle. GetType ());
Vehicle. DescribeCar ();

System.Console.WriteLine ("----------");

}

The output of this loop is as follows:

Car Object:YourApplication.Car

Four wheels and an engine.

----------

Car Object:YourApplication.ConvertibleCar

Four wheels and an engine.

----------

Car Object:YourApplication.Minivan

Four wheels and an engine.

Carries seven people.

----------

Note that the Convertiblecar description may not be the same as what you expected. Because the new keyword is used to define this method, it is not called a derived class method, but a base class method. The minivan object calls the overridden method correctly and produces the expected result.

C # Fundamentals (base, this, new, override, abstract, virtual, static)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.