VB.net Study Notes (14) reflection, Polymorphism

Source: Internet
Author: User

Like remote control, reflection enters the peer computer and returns relevant information from the peer computer.

Therefore:

First: Ask the other party to support (or allow) the entry (reflection is a technology built in. Net framwork)

Second: there must be some way to enter (system. Reflection to get another assembly or Class)

To put it simply, reflection is used to obtain relevant information (such as classes, fields, attributes, and methods) in another assembly)

Reflection is also associated with polymorphism. Next, let's take a look at the situation.

I. Post-binding implementation of Polymorphism

 

Polymorphism: two classes have the same set of methods, attributes, and events while having different implementation codes.

In this way, you can write a universal interface calling program (without worrying about whether it is a Class A or B class)

In terms of polymorphism, later binding is based on the Code to reduce the performance and programming to achieve pure polymorphism.

Create a new project ooexample and add the class encapsulation as follows:

Imports System.MathPublic Class Encapsulation    Private mX As Single    Private mY As Single    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single        Return CSng(Sqrt((x - mX) ^ 2 + (y - mY) ^ 2))    End Function    Public Property CurrentX() As Single        Get            Return mX        End Get        Set(ByVal value As Single)            mX = value        End Set    End Property    Public Property CurrentY() As Single        Get            Return mY        End Get        Set(ByVal value As Single)            mY = value        End Set    End PropertyEnd Class

Add a form button and click code:

Public Class Form1    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        Dim obj As New Encapsulation        MsgBox(obj.DistanceTo(10, 10))    End SubEnd Class

OBJ is a strong type, that is, a specific type. The compiler can determine it before compilation, so it is also called "pre-binding"

Later binding is used as follows:

Post-binding: The type (Object Type in the following example) cannot be determined before compilation, and the type (New encaplsulation) must be determined at runtime. This is called post-binding. The code for changing the form is as follows:

Public Class Form1    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        Dim obj As Object = New Encapsulation        MsgBox(obj.DistanceTo(10, 10))    End SubEnd Class

NOTE: If option strict on is used, the type is strictly checked and cannot be bound later. Therefore, you should disable it to allow later binding.

Later binding dynamically determines the actual object type in the background and calls appropriate methods.

When an object is used, the IDE and compiler cannot determine whether the called method is correct (for example, whether the above OBJ has the distanceto method ).

It can only be determined by humans to have this Member (in this case, the intelligent prompt that intelliisense will be invalid)

Moreover, the later binding has serious performance losses (whether each method exists at runtime can be determined and will take time)

In addition, calling through later binding is not as efficient as calling methods known at compilation (pre-binding.

Separate the preceding form code into common methods and call them again:

Public Class Form1    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        Dim obj As New Encapsulation        ShowDistance(obj)    End Sub    Private Sub ShowDistance(ByVal obj As Object)        MsgBox(obj.DistanceTo(10, 10))    End SubEnd Class

The object type parameter is used in the same method and is also bound later. If the input does not match, an error occurs.

The following describes the later binding polymorphism:

Add the new class poly to the above project:

Public Class Poly    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single        Return x + y    End FunctionEnd Class

Note: like the encapsulation class, the distanceto method also exists, and the method signature is the same.

You can also call the showdistance method to change the code by pressing the key in the form:

Public Class Form1    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        Dim obj As New Poly        ShowDistance(obj)    End Sub    Private Sub ShowDistance(ByVal obj As Object)        MsgBox(obj.DistanceTo(10, 10))    End SubEnd Class

As you can see, although the object passed to the showdistance method may be of the poly or encapsulation type, the code runs normally.

As mentioned above, calling different objects through methods achieves the polymorphism of later binding.

2. multi-interface Implementation of Polymorphism

 

Later binding is flexible and simple, but resources are charged, and the IDE and compiler are not allowed to perform type checks during design. Smart sensing fails and cannot check input errors.

Multiple interfaces are used. The IDE and compiler can check the code During input and compilation, and can be used intelligently. At the same time, you can confirm the type to make code execution faster.

To put it simply, multiple interfaces are a strong type and are pre-bound.

Add multiple interfaces for the above project:

Add a module and create an interface ishared in it:

Public Interface IShared    Function CalculateDistance(ByVal x As Single, ByVal y As Single) As SingleEnd Interface

Improve the ishared interfaces in the encapsulation class and poly class:

Imports System.MathPublic Class Encapsulation    Implements IShared    Private mX As Single    Private mY As Single    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single Implements IShared.CalculateDistance        Return CSng(Sqrt((x - mX) ^ 2 + (y - mY) ^ 2))    End Function    Public Property CurrentX() As Single        Get            Return mX        End Get        Set(ByVal value As Single)            mX = value        End Set    End Property    Public Property CurrentY() As Single        Get            Return mY        End Get        Set(ByVal value As Single)            mY = value        End Set    End PropertyEnd ClassPublic Class Poly    Implements IShared    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single Implements IShared.CalculateDistance        Return x + y    End FunctionEnd Class

Add another showdistance Method to the form. Note that its type is ishared and the object parameter with the same name is reloaded.

The clicking event also changes:

Public Class Form1    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        Dim obj As New Poly        Dim obj1 As IShared = obj        ShowDistance(obj)        ShowDistance(obj1)    End Sub    Private Sub ShowDistance(ByVal obj As Object)        MsgBox(obj.DistanceTo(10, 10))    End Sub    Private Sub ShowDistance(ByVal obj As IShared)        MsgBox(obj.CalculateDistance(10, 10))    End SubEnd Class

Both call the last one because it is "the most matched ". (The program runs normally after the comment)

You can see:

Multiple Interfaces implement polymorphism, as long as the general method (the last one above) is written, any object can be used as long as the interface is the same.

It also shows that not only inheritance is used for polymorphism, but different objects can also be polymorphism!

Iii. polymorphism of reflection

Getting started with reflection in. net

Http://blog.csdn.net/timmy3310/article/details/12615

Use and Analysis of reflection mechanisms in. net
Http://www.cnblogs.com/focusonnet/archive/2009/04/17/1438013.html

The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect, and modify its own state or behavior.

The proposal of this concept soon led to research on application reflectivity in the computer science field. It is first adopted by the design field of programming language, and in LISP

And object-oriented. Lead/Lead ++, openc ++, metaxa, and openjava are reflection-based languages.

Recently, reflection mechanisms have been applied to Windows, operating systems, and file systems.

Reflection itself is not a new concept. It may remind us of the concept of reflection in optics, although computer science has given a new meaning to the concept of reflection,

However, in terms of phenomena, they do have some similarities that help us to understand.

In computer science, reflection is a type of application that can be self-described and self-controlled. That is to say, this type of application uses a certain mechanism to implement

Behavior description (self-representation) and monitoring (examination), and can adjust or modify the description line of the application according to the status and results of the behavior.

Status and related semantics.

We can see that, compared with the general reflection concept, reflection in the computer science field not only refers to reflection itself, but also measures taken to reflect the results. All adopt

The reflection system (that is, the reflection system) wants to make the system more open. It can be said that all systems implementing reflection mechanisms are open, but open.

The system does not necessarily adopt the reflection mechanism. Openness is a necessary condition for the reflection system.

In general, the reflection system must meet both the open conditions and the cause of connection (causally-connected ). The so-called cause connection refers to the self-reflection system

The change in the description can immediately reflect the actual status and behavior of the underlying system, and vice versa. Open connection and cause connection are two basic elements of the reflection system.

Bytes -----------------------------------------------------------------------------------------------------------------------------

Later binding is slow and difficult to debug. There are many restrictions on multiple interfaces, and they are not flexible enough.

Reflection can overcome these shortcomings. Reflection is a technology built in. NET framework that allows you to write code to query. Net assembly.

To dynamically determine the classes and data types it contains. (Instances created only at runtime are dynamic)

Use reflection to load the program into the process, create instances of these classes, and call their methods.

In later binding, VB.net uses system. reflection namespace, which can be used to browse information about an assembly or class to understand these classes, or to manually use reflection to interact with objects for greater flexibility.

Next, add another project based on the original project. The ooexample project uses reflection to view the objects of another project.

File-> Add-> new project, create a class library named objects, and add class external in it:

Public Class External    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single        Return x * y    End FunctionEnd Class

Note: After creation, you must generate-> Generate objects to generate an objects. dll. Prepare for the next step.

In each of the following projects, check whether the corresponding file is generated before debugging.

Reference reflection in the main form and add the following code:

Option strict offimports system. reflection 'reflection namespace public class form1 private sub button#click (sender as object, e as eventargs) handles button1.click dim OBJ as object dim dll as assemb' reflection. assembly type, stores references to the objects assembly (Dynamic Loading below) DLL = assembly. loadfrom (".. \.. \.. \ Objects \ bin \ debug \ objects. DLL ") 'dynamically load OBJ = DLL. createinstance ("objects. external ") 'create the object msgbox (obj. distanceto (10, 10) end sub private sub showdistance (byval OBJ as object) msgbox (obj. distanceto (10, 10) end sub private sub showdistance (byval OBJ as ishared) msgbox (obj. calculatedistance (10, 10) end subend class

Use the Assembly. loadfrom method to dynamically load the external Assembly objects. The reflection library loads the Assembly from the disk. Once the program crashes,

You can use the DLL variable to interact with it, including querying it to obtain the list of classes it contains or to create instances of these classes.

Note: The assemblyload method is also available. This method scans the directory of the EXE file (and Global Assembly Cache) of the application to find the object assembly.

Find the assembly, and load it to the internal for use.

In this example, the key is to define OBJ as the object type and finally use obj. distanceto. After different assembly reflection, instances are converted into different objects as long as they contain distanceto members.

In this way, the general method can be called to achieve the purpose of polymorphism.

Iv. Reflection and multi-interface implementation Polymorphism

The above reflection and multi-interface have implemented their own polymorphism. Below, we will combine these two implementations for polymorphism.

Create a universal interface in the main program and external program (SET), and then dynamically load the external assembly with reflection at runtime.

Continue with the above solution and add related operations. The final solution is as follows (three projects in total)

For more information, see File> Add> new project. Add a new class library named interfaces. In the ooexample project, hold down SHIFT and drag interfaces. VB to the interfaces project, so that the interface ishared in the original ooexample will be moved to the interfaces project.

Right-click ooexample (Project), select Add reference, and select interfaces. (Ooexample references the interface in interfaces because its ishared has been moved to the interfaces project)

Similarly, add the same reference to objects.

In the objects project, add references and interfaces as follows:

Imports InterfacesPublic Class External    Implements IShared    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single Implements IShared.CalculateDistance        Return x * y    End FunctionEnd Class

In the ooexample project poly class, change it to the following code:

Imports InterfacesPublic Class Poly    Implements IShared    Public Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single Implements IShared.CalculateDistance        Return x + y    End FunctionEnd Class

In this way, both ooexample and objects have completed references to the interfaces (Interface) of another project. :

In this way, the main program ooexample and the external program objects can use the same data type (interfaces), then reflected to the external program, converted to the same type (interfaces) after instantiation)

To achieve the effect of polymorphism.

The main program code is as follows:

Imports InterfacesImports System.ReflectionPublic Class Form1    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        Dim obj As Object        Dim dll As Assembly        dll = Assembly.LoadFrom("..\..\..\Objects\bin\Debug\Objects.dll")        obj = CType(dll.CreateInstance("Objects.External"), IShared)        ShowDistance(obj)    End Sub    Private Sub ShowDistance(ByVal obj As Object)        MsgBox(obj.DistanceTo(10, 10))    End Sub    Private Sub ShowDistance(ByVal obj As IShared)        MsgBox(obj.CalculateDistance(10, 10))    End Sub    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load        Me.CustomerBindingSource.DataSource = New Customer    End SubEnd Class

After the above object is dynamically created, it is converted to the ishared type and implemented through showdistance.

Note: Each project above should be generated separately-> xxx should be generated once before running.

The combination of multiple interfaces and reflection makes the code that calls the showdistance method all strongly (ishared), providing a lot of convenience and coding technologies (smart sensing takes effect ),

In addition, DLL and object are dynamically loaded, providing great flexibility for applications.

5. Inheritance implementation Polymorphism

Subclass objects can always be considered as Data Types of parent classes.

Inheritance can achieve polymorphism. Note that polymorphism (such as multiple interfaces) can be implemented without inheritance ).

To illustrate the polymorphism in inheritance, add a base class parent, which is the parent class of the encapsulation class and the poly class. It is a virtual base class:

Public MustInherit Class Parent    Public MustOverride Function DistanceTo(ByVal x As Single, ByVal y As Single) As SingleEnd Class

The corresponding subclass: encapsulation class and poly class are also modified accordingly:

Public Class Encapsulation    Inherits Parent    Implements IShared    Private mX As Single    Private mY As Single    Public Overrides Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single Implements IShared.CalculateDistance        Return CSng(Sqrt((x - mX) ^ 2 + (y - mY) ^ 2))    End Function    '....End ClassImports InterfacesPublic Class Poly    Inherits Parent    Implements IShared    Public Overrides Function DistanceTo(ByVal x As Single, ByVal y As Single) As Single Implements IShared.CalculateDistance        Return x + y    End FunctionEnd Class

Note: You must override the distanceto method of the base class encapsulation.

Modify the following code in the main program:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click        ShowDistance(New Poly)        ShowDistance(New Encapsulation)    End Sub    Private Sub ShowDistance(ByVal obj As Parent)        MsgBox(obj.DistanceTo(10, 10))    End Sub

In this way, the general method can be used as long as the parameter of the showdistance method is a subclass of the parent to achieve polymorphism.

Vi. Summary

Polymorphism can be achieved through many technologies. The following are the advantages and disadvantages of each technology:

Post-binding: Advantages-flexible, with pure polymorphism,

Disadvantages: slowness, difficulty in debugging, and lack of smart sensing

Applicable -- used to call any method of any object without considering the data type or interface.

 

Multiple Interfaces: Advantages: fast, easy to debug, and intelligent sensing.

Disadvantage: it cannot be completely dynamic or flexible. It requires the class creator to implement a unified interface.

Applicable -- used when creating code that interacts with multiple clearly defined methods (these methods can be combined into a formal interface)

Reflection and later binding: Advantage-flexible, pure polymorphism, can dynamically load any assembly of the Disk

Disadvantages: slowness, difficulty in debugging, and lack of smart sensing

Applicable -- if you do not know which assembly will be used during design, use this technology to call any method in any object

Reflection and multiple interfaces: Advantages: fast, easy to debug, smart sensing, and dynamic loading of any assembly in the disk

Disadvantage: it cannot be completely dynamic or flexible. It requires the class creator to implement a unified interface.

Applicable -- when creating code that interacts with a clearly defined method (these methods can be combined into a formal interface), if

I don't know which assembly will be used, so I will use this technology.

Inheritance: Advantages: fast, easy to debug, smart sensing, inheriting the behavior of the fern

Disadvantage: it cannot be completely dynamic or flexible. The class creator must inherit the common base class.

Applicable -- used when there is an inheritance relationship. polymorphism can be achieved through inheritance because inheritance is meaningful, not because only polymorphism is obtained. (That is, inheritance is the purpose, while polymorphism is not the purpose)

Source code storage: http://download.csdn.net/detail/dzweather/5979279

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.