C # improving knowledge-001: Application and principle of reflection (1)

Source: Internet
Author: User
Tags field table

In projects, mutual reference between assemblies is often encountered. For example, the main program references each sub-module, each sub-module references a public assembly, and parallel Assembly also needs to be referenced for implementation of some functions. Such a reference is a mandatory choice, and also reflects the level of system design. Next, we will briefly introduce a mechanism in C #-reflection. Reflection can avoid Assembly reference problems in some situations. For example, if the main program references various functional modules, reflection can also be used between other modules, however, you need to consider whether it is convenient to use these questions according to the actual situation before use. This article takes the main program as an example to introduce the use of reflection. Reflection refers to the process of parsing an assembly or module using the basic type, restoring an object model, and running it in the caller's work domain. The core part is resolution. This is how it works. No matter how complicated a class you create, it is ultimately composed of metadata. As follows: [csharp] public class Person {private string name; private int age; private string content;} during program compilation, the compiler creates a type table and field table, method table or other tables. Use System. the types contained in the Reflection namespace can also be parsed as a comparison process. The tables in the Assembly to be reflected will be read according to System. reflection is the basic type and restructured to restore the structure of the original assembly. For example, the serialization process uses reflection. the serialization formatter obtains the value of the field in the serialized object and then writes it to a byte stream for transmission; because byte stream transmission is not prone to errors or information loss. After the byte stream is received, the model of the original object is restored based on the basic type. In reflection, the System. Type is very important. it traverses the Type in the reflected table and compares it with the basic Type in reflection, and then determines the current Type. A simple understanding of the principle, then let's look at how to use it. Create a project that contains the main program and subroutine set. The main program is generated in the SetupApp folder, and the subroutine is generated in \ SetupApp \ Library. The program entry of the subroutine must follow some conventions. For example, the entry class names must be the same so that they can be loaded in a unified manner. [Csharp] namespace ReflecLibrary2 {public class MainWindow {public MainWindow () {Welcome ();} private void Welcome () {Console. write (@ "current program: ReflecLibrary2"); Console. writeLine (@ "start executing ReflecLibrary2! ") ;}} Namespace ReflectLibrary1 {public class MainWindow {public MainWindow () {Welcome () ;} private void Welcome () {Console. write (@ "current program: ReflectLibrary1"); Console. writeLine (@ "start executing ReflecLibrary1! ") ;}} And then check the calling part. [csharp] class Program {static void Main (string [] args) {// set the agreed rules, such as the Directory of the program to be loaded, class of the assembly program entry // string startPath = AppDomain. currentDomain. baseDirectory + @ "Library \"; string suffix = @". dll "; string commonMainClass = @" MainWindow "; DirectoryInfo directory = new DirectoryInfo (startPath ); /////////////////// read the Assembly file name. Here, you only need a path of the string type, /// // It is convenient to process strings later, so the file information var libraries = directory is read. getFiles (). orderBy (o => o. fullName); List <FileInfo> loadDlls = new List <FileInfo> (); if (libraries! = Null) {foreach (FileInfo item in libraries) {if (item. fullName. toLower (). endsWith (suffix) {loadDlls. add (item );}}} /// // execute the Assembly ///////////////// //// Assembly 1 Assembly assembly1 = Assembly. loadFile (loadDlls [0]. fullName. replace (@ "/", @ "\"); string typeName1 = loadDlls [0]. name. replace (loadDlls [0]. extension, string. empty) + @". "+ commonMainClass; assembly1.CreateInstance (typeName1 ); // Assembly 2 Assembly assembly2 = Assembly. loadFile (loadDlls [1]. fullName. replace (@ "/", @ "\"); string typeName2 = loadDlls [1]. name. replace (loadDlls [0]. extension, string. empty) + @". "+ commonMainClass; assembly2.CreateInstance (typeName2); Console. readLine ();} the functions of each part are written in comments. The running result is that the methods in Assembly 1 and assembly 2 are executed. Of course, only one method is written for convenience. In fact, public MainWindow () {Welcome () ;}is the subprogram entry. The result is as follows. We have an intuitive understanding of the reflection. The detailed principles are described in the next article.

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.