[. Net & #160; advanced object-oriented programming] & #160; (20) & #160; Reflection (Reflection) & #160; Use Reflection technology to implement dynamic programming (I ), javareflection reflection

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (20) Reflection (Reflection) Using Reflection Technology for Dynamic Programming (I), javareflection Reflection

[. Net Object-Oriented programming advanced] (20) Reflection (Reflection) Using Reflection Technology for Dynamic Programming (I)

This section describes what is. NET reflection feature ,. NET reflection can do something for us. Finally, we will introduce several common reflection implementation methods. By understanding the reflective feature, we can design a very useful reflection-based programming mode.

Before reading:

[. Net Object-Oriented Programming Basics] (10) Class Members (fields, attributes, methods)

1. What is. NET reflection?

Reflection is an important feature of. NET. The explanation of. NET reflection in CLR via C # Is that metadata is used to represent storage in our applications. When compiling an assembly or module, the compiler creates a type definition table, a field definition table, a method definition table, and other tables. If we want to dynamically call these metadata tables (or parse these tables), or create an object model for these metadata, this process is reflection.

In short, it is the process of dynamically calling the attributes, fields, methods, and other processes in the compiled Assembly, that is, reflection.

Reflected in. NET, implemented through the class in the System. Reflection namespace.

2. What can reflection do for us?

This problem is the focus of our learning reflection. We have to know the benefits of learning it before we can continue to read this article.

Reflection is indeed a very important and useful feature of. NET.

A. Enumeration type members

B. New Instance Object

C. Execution object Member

D. Search for type information

E. query assembly information

F. Check whether custom features are applied to a certain type.

G. Create and compile a new assembly

H. Simplify the operations on data bound during execution rather than during compilation. (New functions after C #4.0)

In addition, reflection on generics is allowed in the new. NET version.

The above are the basic features of reflection. Refer to C # Essence and C # advanced programming.

Based on the above basic features, we can design many very practical programming modes.

The following lists several instances in reflection-based design mode:

A. Use reflection to create an API document for dynamically creating an assembly. Based on reflection that allows enumeration of type and member features in a set, we can get the field method attribute events and their XML annotations in compiled sets through reflection. This allows you to dynamically create API documents for an assembly;

B. Very common reflection factory models. The reflection factory mode is easy to understand and simple in the design mode. Many code Generators use this design pattern to implement reflection calls from different databases. For example, we have three databases: MsSql, MySql, and Oracle. in the project design, we may change to another database at any time (of course, this is just a hypothesis ), therefore, you need to add, delete, modify, and query classes for these three databases at the same time, that is, the data category class. When switching the database, we only need to change the database type in config. Other work should be handed over to the reflection factory class to dynamically call the corresponding database access method in the compiled assembly.

It doesn't matter if you don't understand it. Here we just describe the reflection application instance to facilitate more confident learning reflection. There should be a lot of reflection in the design pattern, which will not be listed here.

3. Reflection application Basics

The above is nothing more than understanding what reflection can do for us. Let's start with the question and talk about the code implementation of reflection.

The following describes the core classes and class members of reflection.

Reflected namespace: System. Reflection

Most of the reflected classes are in this namespace.

Main class: System. Type

This class is the core of reflection, and its attribute method can obtain runtime information.

The Type class is derived from the System. Reflection. MemberInfo abstract class.

Read-only attribute in the MemberInfo class

Attribute

Description

Remarks

Type DeclaringType

Obtains the type of the class or interface that declares the member.

 

MemberTypes MemberType

Gets the type of a member. This value indicates that the member is a field, method, attribute, event, or constructor.

This is an enumeration that defines the type values used to represent different members. These values include: MemberTypes. Constructor, MemberTypes. Method, MemberTypes. Field, MemberTypes. Event, and MemberTypes. Property. Therefore, you can check the MemberType attribute to determine the Member type. For example, when the value of the MemberType attribute is MemberTypes. Method, the member is a Method.

Int MetadataToken

Obtain values related to specific metadata

 

Module

Obtains a Module object that represents the Module (Executable File) where the reflection type is located.

 

String Name

Member name

 

Type ReflectedType

Reflected object type

 

Read-only attribute of Type

Attribute

Description

Assembly

Obtains an assembly of the specified type.

TypeAttributes Attributes

Obtain the features of the specified type

Type BaseType

Obtains the direct base type of the specified type.

String FullName

Obtains the full name of a specified type.

Bool IsAbstract

Returns true if the specified type is abstract.

Bool IsClass

Returns true if the specified type is a class.

String Namespace

Obtains the specified namespace.

 

Type Method

Method

Description

ConstructorInfo [] GetConstructors ()

Returns the list of constructors of the specified type.

EventInfo [] GetEvents ();

Obtains a Time column of the specified type.

FieldInfo [] GetFields ();

Obtains a field column of the specified type.

Type [] GetGenericArguments ();

Obtains the list of type parameters bound to a constructed generic type. If you specify a generic type definition, you can obtain the type parameters. For the type constructed earlier, the list may contain both the type real parameters and the type form.

MethodInfo [] GetMethods ();

Returns a list of methods of the specified type.

PropertyInfo [] GetProperties ();

Get the attribute list of the specified type e

MemberInfo [] GetMembers ();

Obtains the list of members of the specified type.

There are many classes for reflection, which are not described here. For details, refer to MSDN:

Https://msdn.microsoft.com/zh-cn/library/system.reflection.aspx

4. Reflection instance

The following example shows how to use reflection.

Create a solution that contains two projects. The project ClassLibrary generates a DLL (including two classes), and the other project is ReflectionTestGet, which is used to reflect the ClassLibrary of the call class.

The two classes of the first project are as follows:

MartialArtsMaster. cs

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ClassLibrary {// <summary> // class: martial arts master /// MartialArtsMaster /// </summary> class MartialArtsMaster {/// <summary> /// level /// </summary> public int _ level = 9; /// <summary> /// No. /// </summary> public int Id {get; set ;} /// <summary> /// Name /// </summary> public string Name {get; set ;} /// <summary> /// Age /// </summary> public int Age {get; set ;} /// <summary> /// martial // </summary> public string Menpai {get; set ;} /// <summary> /// Wuxue /// </summary> public string Kungfu {get; set ;} /// <summary >/// Level /// </summary> public int level {get {return _ level;} set {_ Level = value ;}} /// <summary> /// attack /// </summary> /// <param name = "kungfu"> </param> /// <returns> </ returns> public string Attack (string kungfu) {return "has been used:" + kungfu;} public string Kill (string kungfu, string name) {return: "+ kungfu +" killed "+ name ;}}}View Code

Person. cs

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ClassLibrary {// <summary> // class: Person /// </summary> class Person {public string gender {get; set ;} public string race {get; set;} public string Country {get; set;} public string Eat (string strCountry) {switch (strCountry) {case "case ": return "eat western food"; case "Korea": return "Eat kimchi"; default: return "do not know ";}}}}View Code

The second project is called as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. reflection; namespace ReflectionTestGet {class Program {static void Main (string [] args) {Assembly asm = Assembly. loadFrom ("ClassLibrary. dll "); // load the specified assembly Type [] alltype = asm. getTypes (); // obtain the list of all types in the Assembly foreach (Type calssName in alltype) {Console. writeLine ("set Class Name of the loader:" + calssName. name); // print out all the class foreach (var field in calssName. getFields () Console. writeLine (calssName. name + "fields:" + field. name); // print all fields of the Assembly. Note that only the public field foreach (var pro in calssName. getProperties () Console. writeLine (calssName. name + "attributes:" + pro. name); // print out all attributes of the Assembly. foreach (var met in calssName. getMethods () Console. writeLine (calssName. name + "Methods:" + met. name); // print all methods of the Assembly} Console. readKey ();}}}View Code

The running result is as follows:

5. Highlights of this section:

This section describes the usage of reflection and the basic operations and attribute methods of reflection. Next, we will continue to introduce how to apply reflection technology to actual projects.

========================================================== ========================================================== ====================

 Returned directory

<If it is helpful to you, please click here for recommendations. If yes

Do not understand or make a mistakePoints, Please exchange more>

<If you have any difficulty reading this series of articles, please read. net Object-Oriented Programming basics first>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

========================================================== ========================================================== ====================

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.