C # reflection technology

Source: Internet
Author: User

Dynamic Loading and usage types
Http://msdn2.microsoft.com/zh-cn/library/k3a58006 (vs.80). aspx
Http://blog.csdn.net/zjghd/archive/2006/09/27/1292739.aspx reflection details
Chapter 4 reflection of Reading Notes

 
// Obtain the eventinfo object by calling getevent and naming eventEventinfo = type. getevent ("Publicevent", Bindingflags. Public | bindingflags. instance );// Call addeventhander through the eventinfo object. Addeventhander must be associated with the instanceProgramObject, and system. delegate is composed and initialized by the method address that complies with the eventhandler signature.Eventinfo. addeventhandler (instance,NewEventhandler (handler ));// Event triggering MethodInstance. doevent ();


Learning reflection mechanism C #Examples

Console. writeline ( " List all types in a dataset " );

Assembly = Assembly. loadfrom ( " Reflectionexample.exe " );

Type [] mytypes = A. gettypes ();

Foreach (Type T In Mytypes)

{

Console. writeline (T. Name );

}

Console. writeline ( " List all methods in helloworld " );

Type HT =   Typeof (Helloworld );

Methodinfo [] MIF = Ht. getmethods ();

Foreach (Methodinfo MF In MIF)

{

Console. writeline (MF. Name );

}

Console. writeline ( " Instantiate helloworld and call the helloworld Method " );

Object OBJ = Activator. createinstance (HT );

String [] S =   {"Wssmax"} ;

Object objname = Activator. createinstance (HT, S );

Methodinfo msayhello = Ht. getmethod ( " Sayhello " );

Msayhello. Invoke (OBJ, Null );

Msayhello. Invoke (objname, Null );

Console. Readline ();

1. Reflection Overview

Public Language Runtime LibraryLoader ManagementApplication domain. Such management includes loading each assembly to the corresponding application domain and controlling the memory layout of the type hierarchy of each set.

 

 

 

 

AssemblyContains modules, while modules include types and types include members. Reflection provides encapsulated assembly, module, and type objects. You can use reflection to dynamically create instances of the type, bind the type to an existing object, or obtain the type from an existing object. Then, you can call methods of the type or access its fields and attributes. Reflection is usually used for the following purposes:

 

 

 

 

  • use Assembly defines and loads the Assembly, loads the modules listed in the assembly list, and searches for the type from this Assembly and creates instances of this type.

  • UseModuleUnderstand the following similar information: including the assembly of the module and the class in the module. You can also obtain all global methods defined on the module or other specific non-Global methods.

     

  • Use Constructorinfo Learn the following similar information: name, parameter, and access modifier of the constructor (for example Public Or Private ) And implementation details (such Abstract Or Virtual . Use Type Of Getconstructors Or Getconstructor Method to call a specific constructor.

     

  • Use Methodinfo To understand the following similar information: method name, return type, parameter, access modifier (such Public Or Private ) And implementation details (such Abstract Or Virtual . Use Type Of Getmethods Or Getmethod Method to call a specific method.

     

  • Use Fieldinfo To understand the following similar information: field name, access modifier (such Public Or Private ) And implementation details (such Static ), And obtain or set the field value.

     

  • use eventinfo to learn the following similar information: event name, event processing program data type, custom attribute, declaration type, and reflection type; and add or remove event handlers.

  • use propertyinfo to learn the following similar information: attribute name, data type, declaration type, reflection type, read-only or writable status, and get or set the attribute value.

  • UseParameterinfoTo understand the following information: the parameter name, data type, whether the parameter is an input parameter or an output parameter, and the position of the parameter in the method signature.

     

System. reflection. emitThe namespace class provides a special form of reflection, allowing you to construct types at runtime.

 

 

 

 

Reflection can also be used to create an application called a type browser. It allows you to select a type and view information about the selected type.

 

 

 

 

Reflection has other functions.JScriptAnd other language compilers use reflection to construct symbol tables.System. runtime. serializationThe classes in the namespace use reflection to access data and determine the fields to be permanently saved.System. runtime. remotingClasses in The namespace use reflection indirectly through serialization.

2.Dynamically add and use Types

Reflection provides a language compiler (for exampleMicrosoft Visual Basic. netAndJScript) Is used to implement the underlying structure of implicit late binding. Binding is the process of finding the declaration (Implementation) corresponding to the unique specified type. Because this process does not occur during compilation at runtime, it is called late binding.Visual Basic. netYou canCodeUsing implicit late binding;Visual BasicThe compiler calls a helper method that uses reflection to obtain the object type. Parameters passed to the helper method help call the correct method at runtime. These parameters include the instance (object) of the method to be called, the name (string) of the called method, and the parameters (Object array) passed to the called method ).

 

 

In the following exampleGetdatasetMethod,Parameters required for this methodString userid

 

 

Assembly assembly;

 

 

Type type;

 

 

StringDllpath = @ "D: \ test \ powerspace. VCP. Utility. dll ";

 

 

Try

 

 

{

 

 

Assembly = assembly. LoadFile (dllpath );

 

 

Type = assembly. GetType ("powerspace. VCP. Utility. cmystring ",True,True);// Cmyresult

 

 

}

 

 

Catch(Filenotfoundexception)

 

 

{

 

 

Response. Write ("cocould not load Assembly: \" "+ dllpath + "\"");

 

 

Return null;

 

 

}

 

 

Catch(Typeloadexception)

 

 

{

 

 

Response. Write ("cocould not load type: \" string \ "\ n from assembly: \" "+ dllpath + "\""); Return null;

 

 

}

 

 

Methodinfo method = type. getmethod ("testinvoke ");

 

 

ObjectOBJ = assembly. getassembly (type). createinstance ("powerspace. VCP. Utility. getdataset ");

 

 

 

 

ObjectS = method. Invoke (OBJ,New Object[] {"Jiangli "});

 

 

DatasetSs = (Dataset) S;

 

 

Assembly =Null;

 

 

Type =Null;

 

 

Method =Null;

 

 

Return SS;

 

 

 

 

3.Access Custom Attributes

The access custom attributes are the same as the dynamic addition and use types..

 

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.