Delegates in polymorphic C # in C #

Source: Internet
Author: User

I believe everyone is familiar with the object-oriented three feature encapsulation, inheritance, polymorphism, everyone can say one or two sentences, but most of them just know what these are, do not know how the CLR is implemented internally, so this article is mainly about the polymorphism of some of the concepts have been implemented within the mechanism. I. The concept of polymorphismFirst explain what is called polymorphism: the same action works on different objects, can have different interpretations, and produces different execution results, which is polymorphism. In other words, it is actually the same type of instance that invokes the "same" method, resulting in a different result.          Here the "Same" is used to double quotation marks because the same method here is just the same method that looks the same, in fact they call the method is different. When it comes to polymorphism, we can't mundane mention the following concepts: overloading, rewriting, virtual methods, abstract methods, and hidden methods.        Here's a brief introduction to their concept. 1. overloading (overload): two or more method function names of the same scope (generally referred to as a Class) are the same, and the parameter list differs by the method called overloading, they have three characteristics (commonly known as two must be one):
    • Method names must be the same
    • Parameter list must be different
    • Return value types can be different
Such as:
        public void Sleep ()        {            Console.WriteLine ("Animal Sleeps");        }        public int sleep (int time)        {            Console.WriteLine ("Animal{0} points to sleep", time);            return time;        }

2. override (Override): Subclasses define different implementations of a method in order to meet their own needs, with the override keyword, the overridden method must be a virtual method, with the virtual keyword. It is characterized by (three identical):
    • The same method name
    • The same argument list
    • The same return value.
such as: the definition in the parent class:
        public virtual void Eatfood ()        {            Console.WriteLine ("Animal Eats");        

Definitions in subclasses:
        public override void Eatfood ()        {            Console.WriteLine ("Cat Eats");            Base. Eatfood ();        }
Tips: There are often children's shoes to ask the difference between overloading and rewriting, and the network on the difference between the two as C # to do a common test of one of the face. In fact, these two concepts have nothing to do with it, only with a "heavy" word. They do not have the meaning of comparison, just distinguish their different definitions just fine.
3. virtual Method: The virtual keyword is used to define a method that is defined in a base class that is allowed to be overridden in a derived class. Such as:
        public virtual void Eatfood ()        {            Console.WriteLine ("Animal Eats");        }

Note: Virtual methods can also be called directly. Such as:
            Animal a = new Animal ();            A.eatfood ();

Operation Result:

4. Abstract Methods: A method that is defined in a base class and must be overridden in a derived class, using the abstract keyword definition. Such as:
    Public abstract class Biology    {public        abstract void Live ();    public class Animal:biology    {public        override void Live ()        {            Console.WriteLine ("Animal Overridden abstract method");            //throw New NotImplementedException ();        }     }

Note: Abstract methods can only be defined in abstract classes, and if not defined in an abstract class, the following error is reported:

The difference between a virtual method and an abstract method is that because an abstract class cannot be instantiated, there is no way for an abstract method to be called, which means that an abstract method can never be implemented.
5. Hide Method: A method defined in a derived class that has the same name as a method in a base class, defined using the New keyword. As in the base class animal there is a method of sleep ():
        public void Sleep ()        {            Console.WriteLine ("Animal Sleep");        }

The code that defines the hidden method in the derived class cat is:
        New public void Sleep ()        {            Console.WriteLine ("Cat Sleep");        }

or for:
        Public new void Sleep ()        {            Console.WriteLine ("Cat Sleep");        }    

Note: (1) The Hidden method hides the virtual methods in the base class, and it can also hide the non-virtual methods in the base class.                  (2) The instance of the parent class in the hidden method calls the method of the parent class, and the instance of the subclass calls the method of the subclass.         (3) and the previous comparison: The method of overriding the sub-class variable calls the subclass override method, the parent class's variable depends on whether the parent refers to an instance of a subclass or an instance of itself, if the reference is an instance of the parent class, call the method of the base class, or invoke the method of the derived class if it refers to an instance of Well, the basic concept is over, let's look at an example, we'll start with a few new classes:
    Public abstract class Biology {public abstract void Live (); } public class Animal:biology {public override void Live () {Console.WriteLine ("Animal Override            Live ");        throw new NotImplementedException ();        } public void Sleep () {Console.WriteLine ("Animal Sleep");            } public int sleep (int time) {Console.WriteLine ("Animal at {0} point sleep", time);        return time;        } public virtual void Eatfood () {Console.WriteLine ("Animal Eatfood"); }} public class Cat:animal {public override void Eatfood () {Console.WriteLine ("Cat            Eatfood "); Base.        Eatfood ();        } New public void Sleep () {Console.WriteLine ("Cat Sleep");        }//public new void Sleep ()//{//Console.WriteLine ("Cat Sleep");       }} public class Dog:animal { public override void Eatfood () {Console.WriteLine ("Dog Eatfood"); Base.        Eatfood (); }    }

Here's a look at the code that needs to be executed:
    Class program    {        static void Main (string[] args)        {            //animal instance            Animal a = new Animal ();            Example of Animal, referencing a derived class Cat object            Animal ac = new Cat ();            An instance of Animal that references the derived class Dog object            Animal ad = new Dog ();            Cat's instance            cat C = new Cat ();            Dog's instance            dog d = new Dog ();            Heavy            -duty a.sleep ();            A.sleep (+);            Rewrite and virtual method            A.eatfood ();            Ac. Eatfood ();            Ad. Eatfood ();            Abstract method            a.live ();            Hidden method            a.sleep ();            Ac. Sleep ();            C.sleep ();            Console.readkey ();        }    }

First, we define several instances of the classes we need to use, noting that (1) The biology class is abstract and cannot be instantiated, and (2) The variable AC is an instance of animal, but points to a cat object. Because the cat type is a derived class of type animal, there is no problem with this conversion.         This is also the focus of polymorphism. Let's take a step-by-Step Analysis: (1)
            Heavy            -duty a.sleep ();            A.sleep (23);

Obviously, the two sleep methods called by the animal variable A are overloaded, the first one calls the parameterless sleep () method, and the second sentence calls the sleep method with an int parameter.        Note that the return value of the two sleep methods is different, which also illustrates the last feature in the overridden three features-the return value can be different. The results of the operation are as follows:

(2)
            Rewrite and virtual method            A.eatfood ();            Ac. Eatfood ();            Ad. Eatfood ();

In this section, A, AC, and ad are animal instances, but they refer to different objects, a refers to the animal object, AC refers to the Cat object, ad refers to the dog object, this difference will result in the execution of what difference, see the results of the execution:

The first sentence animal instance, directly calls animal's virtual method Eatfood, without any problems. In the second to third sentence, although they are also examples of animal, they point to the cat and dog objects respectively, so the Eatfood methods that are overridden in the cat class and the dog class are called as if the cat instance and the dog instance call the Eatfood method directly.         This is the manifestation of polymorphism: the same operation works on different objects, can have different interpretations, and produce different execution results. (3)
            Abstract method            a.live ();

This is relatively simple, is to directly rewrite the parent class biology in the live method, the result is as follows:

(4)
            Hidden method            a.sleep ();            Ac. Sleep ();            C.sleep ();

When you analyze hidden methods, you compare them to virtual methods and overrides to each other. Variable A calls the Sleep method of the Animal class and the variable C calls the Cat class's sleep method without objection, but the variable AC refers to a cat type object, should it call the Eatfood method of the Animal type, or the cat type E How about the Atfood method? The answer is to call the Eatfood method of the parent class, which is animal. The results of the implementation are as follows:

Most of the articles are introduced here, just to let us know the concepts and methods of invocation, without stating why. Let's go deeper and talk about the mechanics behind polymorphism. Ii. in-depth understanding of polymorphismTo get a deeper understanding of polymorphism, start with value types and reference types. We all know that the value type is saved on the thread stack, and the reference type is stored in the managed heap.        Because all classes are reference types, we only look at reference types. Now go back to the example of the main function when the entry of the program, when the JIT compiler compiles the main function to a local CPU designation, finds that the method references biology, Animal, Cat, and dog classes, so the CLR creates several instances to represent the types themselves, We call it "type Object".        The object contains a static field in the class, a method table containing all the methods in the class, and two additional members for all objects in the managed heap-the type object point and the synchronization block index. Perhaps the above is not understood for some children's shoes that have not read the relevant CLR books, so let's draw a picture to describe:

The diagram above is what the CLR did before executing the main function, and the main function is executed below (for convenience, the main function is simplified):
            Example of Animal            Animal a = new Animal ();            Example of Animal, referencing a derived class Cat object            Animal ac = new Cat ();            An instance of Animal that references the derived class Dog object            Animal ad = new Dog ();            A.sleep ();            A.eatfood ();            Ac. Eatfood ();            Ad. Eatfood ();

The following instantiates three animal instances, but they actually point to animal objects, cat objects, and dog objects, such as:

Note that while the variable AC and ad are all animal types, pointing to the Cat object and the dog object is the key. When executing a. Sleep (), because sleep is a non-virtual instance method, the JIT compiler finds the type Object (Animal) corresponding to the type of the variable (a) that made the call (the Animal type Object).        Then call the Sleep method in the type object, and if the type object does not have a sleep method, the JIT compiler looks for the sleep method in the base class of the class (all the way to object). When performing AC. Eatfood, because Eatfood is a virtual instance method, the JIT compiler calls to generate some extra code in the method that first checks the calling variable (AC), and then follows the reference address of the variable to find the object that made the call (the Cat object). Locate the Type object (Cat type Object) corresponding to the object that emitted the call, and finally find the Eatfood method in the Type object.         Similarly, if the Eatfood method is not found in this type of object, the JIT compiler looks back into the base class of the type object.   Described above is the JIT compiler in the invocation of the type of non-virtual instance method and the actual situation of the different methods of execution, and this is a different way to deal with these two kinds of methods caused by the surface of the object we see one of the three characteristics-polymorphism. -----A delegate in C #

Personally, it can be understood from the following 2 points:

(1) from the data structure, the delegate is the same as the class is a user-defined type .

(2) In terms of design patterns, a delegate (class) provides an abstraction of a method (object).

A delegate is an abstraction of a method that stores the address of a series of methods that have the same signature and return type. When the delegate is invoked, all the methods contained by the delegate are executed.

PublicDelegateintmydelegate(string s);

The above delegate can be used to refer to any one method with a single string parameter and return an int type variable

2. Delegate definition
delegate void Mydel (int x);

Delegate type declaration:

(1) Start with the Deleagate keyword.

(2) return type + delegate type name + parameter list.

3. Declaring a delegate variable
Mydel Del1,del2;

4. Initialize the delegate variable

(1) using the new operator

The operands of the new operator are composed of the following:

    • Delegate type name
    • A set of parentheses that contains the name of the method that is the first member in the invocation list. The method can be an instance method or a static method.
Del1 = new Mydel (myinstobj.mym1);d El2 = new Mydel (SCLASS.OTHERM2);

(2) using the shortcut syntax

The fast key syntax, which is composed only of the method specifiers. This is possible because there is an implicit conversion between the method name and its corresponding delegate type.

Del1 = Myinstobj.mym1;del2 = Sclass.otherm2;

5. Assignment delegation

Since the delegate is a reference type, we can change the method address reference contained in the delegate variable by assigning it a value. Old references are reclaimed by the garbage collector.

Mydel Del;del = myinstaobj.mym1; Delegate initialization del = sclass.otherm2;//delegate re-assignment, old reference will be recycled

6. Combination of Delegates

Delegates can be combined by using additional operators. This operation eventually creates a new delegate whose invocation list is a connection to a copy of the delegate invocation list of two operands.

The delegate is constant, and the operand is not changed after the delegate is created. A copy of the operand is copied by the delegate combination .

Mydel del1 = Myobj.mymethod; Mydel Del2 = Sclass.otherm2; Mydel del3 = Del1 + Del2;   Combination invocation List

7. Delegate Plus and minus operations

You can use the + = operator to add a method to a delegate.

You can also remove a method from a delegate by using the-= operator.

Mydel del = Myobj.mymethod;del + = Sclass.otherm2; Add Method del-= Myobj.mymethod; Remove method

8. Delegate invocation

A delegate invocation is similar to a method call. After the delegate is called, each method of the invocation list is executed.

before invoking a delegate, you should determine whether the delegate is empty . Calling an empty delegate throws an exception.

if (null! = del) {     del ();//Delegate Invocation}

Delegates in polymorphic C # in C #

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.