Basic reflection usage

Source: Internet
Author: User

1. reflection technology Basics

2. Type class

3. dynamic image creation and method calling

 

1. reflection technology Basics

Reflection is an important technique in. net. reflection can obtain various types of information at runtime, including methods, attributes, events, and constructors. You can also obtain the name, access permission, and parameters of each member.ProgramIn the metadata of the set, the objects processed by reflection are like assembly metadata. Using Reflection technology, you can understand every type. With the relevant information of the type, you can dynamically create the object, call methods, set attributes, and stimulate events when the program is running. All these are not completed during compilation .. NET framework even provides a method to directly create an assembly (assembly) in the memory during runtime to add type to the Assembly ), use ilgenerator to directly inject the Il command to the type method and execute it directly.

. Net assembly hierarchy
C # A program consists of one or more source files. Type is declared in the program. The type includes "members" (Member). For example, a typical class contains methods, attributes, fields, events, and other Members, and can be organized by namespace. Classes and interfaces are examples of types. When C # programs are compiled, they are packaged as assembly ),
A collection usually has a file extension name. .exe or. dll. The former is an independent executable program, and the latter must be loaded into a process, includingCodeTo be executed.
Each assembly is composed of one or more modules (Moudle). The module contains il commands and resources, but does not contain the Assembly List, which exists in the form of an EXE or DLL file.
In most cases, an Assembly contains only one module. In other words, a module File (DLL or EXE) is the Assembly itself.

NET framework expresses the above concepts in a series of Types

Type name Description
Assembly Assembly
Module Module
Constructorinfo Constructor
Methodinfo Method
Fieldinfo Field
Propertyinfo Attribute
Eventinfo Event
Parameterinfo Parameters

 

Each specific assembly is represented by an assembly class instance. The Assembly class provides some static methods for obtaining reference to this object.

Obtains the reference of an assembly of a specific type: console. writeline (assembly. getassembly (typeof (Program )). location); // The Program is a defined class and can also be used: console. writeline (typeof (Program) assembly. location );

Obtain the Assembly reference that contains the code being executed: console. writeline (assembly. getexecutingassembly (). Location );

Get entry Assembly reference: Entry Assembly refers to the Assembly first started in the default application domain of the process, such as the Assembly where the main method in the console application is located, if it is another application domain, it usually refers to the first assembly executed by this application domain to call the executeassembly method. Run the following code to output the complete address console. writeline (assembly. getentryassembly (). Location) of the Entry assembly in the current application domain );

 

 

 

2. Type class

type is a special data type. All data types have their own specific information.
first, let's take a look at the Code
public class myclass
{< br> Public int myfield;
Public void mymethod () {}< br> Public String myproperty {Get; Set ;}< BR >}< br> class Program
{< br> static void main (string [] ARGs)
{< br> myclass OBJ = new myclass (); // create an object
// obtain a type object
type typ = obj. getType ();

// name of the output class
console. writeline (typ. name);
// determines whether it is public
console. writeline (typ. ispublic);
// checks whether two objects belong to the same type.
console. writeline (isthesametype (OBJ, new myclass ();
console. readkey ();

}
Static bool isthesametype (Object obj1, object obj2)
{
Return (obj1.gettype () = obj2.gettype ());
}
}

The above code first creates an object of the myclass type, and obtains a object of the type by calling the GetType method (inherited from the object class, based on this image, you can know the type name of the myclass type, whether it is public or not, and determine whether two pairs belong to the same type, you can directly compare whether the type object is the same. For details, see the isthesametype method.

Create a type object

Create
All data types in. NET Framework are derived from the object class, while the object class provides the GetType method. Therefore, you can call the GetType deduction method to obtain the data type information of the object.
Int I = 100;
Type type = I. GetType ();
Console. writeline (type. Name); // The output is int32.

Create with language keywords
C # provides a typeof object. You can directly obtain the corresponding type object based on the data type.
For example, type = typeof (INT );

Obtain the type using the input parameter name
GetType has several overload forms,
Public static type GetType (string name). Note that the input parameter must be a complete type qualified name, such as "system. int32 "instead of" int32"
Sample Code:
Namespace mynamespace
{
Namespace childspace
{
Public class Outer
{
Public class inner {}
}
}
}
The above code gets the type object of the outer: Type type = type. GetType ("mynamespace. childspace. Outer ");
In the above Code, there is also a class inner, and all the code is inside the class. This class is called an internal class or nested class, and the type name of the internal class is constructed using +,
Type type3 = type. GetType ("mynamespace. childspace. Outer + inner ");

After obtaining the type object, you can use its methods to obtain various information about the specific data type. The following sample code obtains the myclass. each member of the DLL class userinfo is displayed on the form. The result is as follows:

// Myclass is defined as follows
Namespace myclass
{
Public class userinfo
{
String strt;
Public userinfo ()
{
Strt = "AAA ";
}
Public userinfo (string a, string B)
{
Strt = A + B;
}
Public int add (int I)
{
Return I;
}
Public int subtract (int I, Int J)
{
Return I-j;
}
Public string name
{
Get;
Set;
}
Public String age
{
Get;
Set;
}
Public String Tel;
Public String mobile;

}
}
// Obtain the userinfo class members in myclass. dll.
Public void reflecforclass ()
{
Assembly = assembly. loadfrom ("myclass. dll ");
Object OBJ = assembly. createinstance ("myclass. userinfo ");
Type type = obj. GetType ();
// Constructor
Constructorinfo [] cons = type. getconstructors ();
String constructtemp = "";
Foreach (constructorinfo con in cons)
{
Constructtemp + = con. tostring () + "\ r \ n ";
}
Txtconstructor. Text = constructtemp;
// Method
Methodinfo [] meths = type. getmethods ();
String methodtemp = "";
Foreach (methodinfo meth in meths)
{
Methodtemp + = meth. tostring () + "\ r \ n ";
}
Txtmethod. Text = methodtemp;
// Attributes
Propertyinfo [] props = type. getproperties ();
String propertytemp = "";
Foreach (propertyinfo prop in props)
{
Propertytemp + = prop. tostring () + "\ r \ n ";
}
Txtproperty. Text = propertytemp;
// Field
Fieldinfo [] fields = type. getfields ();
String fieldtemp = "";
Foreach (fieldinfo field in fields)
{
Fieldtemp + = field. tostring () + "\ r \ n ";
}
Txtfield. Text = fieldtemp;
}

The methods for retrieving type information of the type class are summarized as follows:

 

 

 3. dynamic image creation and method calling

First, let's look at an example. A four-character generator. This example is developed based on reflection.

First, an interface is defined.
Namespace interfacelib
{
Public interface imathopt
{
Double getit (Double X, Double Y );
}
}
Define another mathlibrary, and define four operations: addition, subtraction, multiplication, and division. All classes implement the imathopt interface in the interface library.
Namespace mathoptlibrary
{
Public class addclass: imathopt
{
Double imathopt. getit (Double X, Double Y)
{
Return X + Y;
}

}
Public class substructclass: imathopt
{
Double imathopt. getit (Double X, Double Y)
{
Return x-y;
}
}
Public class multiplyclass: imathopt
{
Double imathopt. getit (Double X, Double Y)
{
Return x * Y;
}
}

Public class divideclass: imathopt
{
Double imathopt. getit (Double X, Double Y)
{
Return x/y;
}
}
}
Start the project dynamiccreatedobject to reference interfacelib, but you do not need to reference mathlibrary. dll
Private void btnresult_click (Object sender, eventargs E)
{
Imathopt mathopt;
Assembly = assembly. loadfrom ("mathoptlibrary. dll ");
Switch (cbxopt. selecteditem. tostring ())
{
Case "+ ":
Mathopt = (imathopt) Assembly. createinstance ("mathoptlibrary. addclass ");
Break;
Case "-":
Mathopt = (imathopt) Assembly. createinstance ("mathoptlibrary. substructclass ");
Break;
Case "*":
Mathopt = (imathopt) Assembly. createinstance ("mathoptlibrary. multiplyclass ");
Break;
Case "/":
Mathopt = (imathopt) Assembly. createinstance ("mathoptlibrary. divideclass ");
Break;
}
Labresult. Text = mathopt. getit (convert. toint32 (txtnuma. Text), convert. toint32

(Txtnumb. Text). tostring ();
}
When you select an operation from the drop-down box, use the createinstance method of the Assembly class to create the object, and then use it to complete the calculation, the key point of this project is that the dynamiccreatorobject project does not reference the mathlibrary project. It only references the interface library interfacelib. In the main program, the imathopt interface is programmed and no code is bound to the specific type of mathlibrary, this separates the interface code and functional code so that the two can be changed independently. For example, you can provide different user interfaces or use differentAlgorithmImplement the function code, so that the scalability of the entire program is greatly increased, and there will be no such thing as the whole body.

 

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.