C # Reflection Assembly detailed description

Source: Internet
Author: User

1. Understanding of C # reflection mechanism
2, after the concept understanding, must find the method to complete, gives the management main grammar
3, finally give a practical example, reflected out the method in the DLL

Reflection is the process by which an assembly is discovered and run, and the information inside an assembly, such as *.exe or *.dll, can be obtained by reflection. Using reflection, you can see information such as interfaces, classes, methods, fields, properties, attributes, and so on within an assembly. There are several common classes in the System.Reflection namespace that contain multiple reflections, and the following table lists the commonly used classes.
Type action
Assembly can be loaded by this class to manipulate an assembly and get internal information for the Assembly
EventInfo This class to save the given event information
FieldInfo the class to save the given field information
MethodInfo This class to save the given method information
MemberInfo the class is a base class that defines multiple common behaviors for EventInfo, FieldInfo, MethodInfo, PropertyInfo
Module This class allows you to access a given module in multiple assemblies
ParameterInfo This class to save the given parameter information
PropertyInfo the class to save the given property information

First, System.Reflection.Assembly class
With assembly, you can dynamically load assemblies and view the internal information of an assembly, the most common of which is the load () method.
Assembly assembly=assembly.load ("myassembly");
Use the Assembly Object CreateInstance (String) method to reflect the creation of an object, and parameter 0 is the class name.
Second, System.Type class
Type is the most commonly used class, through which you can get internal information for a class, or you can use it to reflect the creation of an object. There are generally three common ways to get a type object.
Using typeof () to get the type Object
Type type=typeof (Example);
Using System.Object.GetType () to get the type Object
Example example=new Example ();
Type Type=example. GetType ();
Using System.Type.GetType () to get the Type object
Type Type=type.gettype ("Myassembly.example", false,true);
Note that parameter 0 is the class name, and Parameter 1 indicates if an exception is thrown if the corresponding class is not found, and parameter 1 indicates whether the class name is case-sensitive
Example:
Our most common is to use reflection to combine with activator to create objects.
Assembly assembly= assembly.load ("myassembly");
Type type=assembly. GetType ("Example");
Object Obj=activator.createinstance (type);
Three, the Reflection method
1. Through System.Reflection.MethodInfo can find the method inside the class

[CSharp]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. Type type=typeof (Example);
    2. Methodinfo[] Listmethodinfo=type. GetMethods ();
    3. foreach (MethodInfo MethodInfo in listmethodinfo)
    4. Cosole.writeline ("Method name is" +methodinfo.name);


2. We can also perform method 2 in the class through the reflection method. We can also execute the method inside the class by means of the reflection method.

[CSharp]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. assembly assembly= assembly.load ( " MyAssembly ");   
    2.    type type=assembly. GetType ( "Example");   
    3.    object obj=activator.createinstance (type);   
    4.     Methodinfo methodinfo=type. GetMethod ( "Hello world")   //get MethodInfo object by method name   
    5.    methodinfo.invoke (obj,//parameter 1 type object[], which represents the corresponding parameter of the Hello world method, and the input value is null for no parameters   


Iv. Reflection Properties
1. You can find the properties within the class by System.Reflection.PropertyInfo
Common methods are GetValue (object,object[]) Get property values and SetValue (object,object,object[]) Set property values
Iv. Reflection Properties
1. You can find the properties within the class by System.Reflection.PropertyInfo
Common methods are GetValue (object,object[]) Get property values and SetValue (object,object,object[]) Set property values
Iv. Reflection Properties
1. You can find the properties within the class by System.Reflection.PropertyInfo
Common methods are GetValue (object,object[]) Get property values and SetValue (object,object,object[]) Set property values

[CSharp]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. Type type=typeof (Example);
    2. Propertyinfo[] Listpropertyinfo=type. GetProperties ();
    3. foreach (PropertyInfo PropertyInfo in listpropertyinfo)
    4. Cosole.writeline ("property name is" + propertyinfo.name);


2. We can also set or get the property value of an object by using the following method 2. We can also set or get the property value of an object by

[CSharp]View PlainCopy
  1. Assembly assembly=assembly.load ("myassembly");
  2. Type type=assembly.  GetType ("Example");
  3. Object Obj=activator.createinstance (type);
  4. PropertyInfo Propertyinfo=obj.    GetProperty ("Name"); //Gets the Name Property object
  5. var name=propertyinfo.getvalue (obj,null); //Get the value of the Name property
  6. PropertyInfo Propertyinfo2=obj.     GetProperty ("age"); //Gets the Age Property object
  7. Propertyinfo.setvalue (obj,34,null); //Set the Age property to


V. Reflection fields
The fields within the class can be found by System.Reflection.FieldInfo
It includes two common methods SetValue (object, Object) and GetValue (object) because the usage method is very similar to the Reflection property and is no longer described here
Slightly
Vi.. Reflective characteristics
by System.Reflection.MemberInfo the GetCustomAttributes (Type,bool) can reflect the characteristics of a class, the following example can reflect all the characteristics of a class
V. Reflection fields
The fields within the class can be found by System.Reflection.FieldInfo
It includes two common methods SetValue (object, Object) and GetValue (object) because the usage method is very similar to the Reflection property and is no longer described here
Slightly
Vi.. Reflective characteristics
by System.Reflection.MemberInfo the GetCustomAttributes (Type,bool) can reflect the characteristics of a class, the following example can reflect all the characteristics of a class

[CSharp]View PlainCopy
    1. Type type=typeof ("Example");
    2. object[] Typeattributes=type.       GetCustomAttributes (false); //Get the properties of the example class
    3. foreach (object attribute in typeattributes)
    4. Console.WriteLine ("Attributes description is" +attribute.  ToString ());


You can get all the attributes of the example class Name property by using the following example to get all the attributes of the example class Name property

[CSharp]View PlainCopy
  1. Public class Example
  2. {
  3. [DataMemberAttribute]
  4. Publics string Name
  5. {get;  set;}
  6. ..................
  7. }
  8. Type type = typeof (Example);
  9. PropertyInfo Propertyinfo=type.    GetProperty ("Name"); //Get the Name property of the example class
  10. foreach (object attribute in Propertyinfo.getcustomattributes (false)) //Traverse all attributes of the Name property
  11. Console.WriteLine ("Property attribute:" +attribute. ToString ());

Summarize:

Assembly.Load () method, Assembly.LoadFrom () method, difference of assembly.loadfile () method
In C #, we want to use reflection, first to understand the relationships of several classes in the following namespaces:
System.Reflection namespaces
(1) AppDomain: An application domain that can be understood as a logical container for a set of assemblies
(2) Assembly: assembly class
(3) Module: Modular class
(4) Type: The most core class for using reflection to get type information
There is a dependency between them, that is, an AppDomain can contain N assembly, a assembly can contain n module, and a module can contain n type.

1,assembly.load ()
This method loads the assembly through the long name of the assembly (including assembly name, version information, language culture, public key token), loads the other assemblies referenced by this assembly, and generally should take precedence over this method, which is much more efficient than LoadFrom. And does not cause the problem of repeated loading (the reason is explained on the 2nd)
With this method, the CLR applies a certain policy to find the assembly, in effect the CLR locates the Assembly in the following order:
⑴ If the assembly has a strong name, first look for the Assembly in the global Assembly Ease (GAC).
⑵ if the strong name of the assembly is not specified correctly or is not found in the GAC, the URL specified by the <codebase> element in the configuration file is searched for
⑶ If a strong name is not specified or cannot be found in the GAC, the CLR probes for a specific folder:
Assuming that your application directory is a privatepath in the c:\appdir,<probing> element that specifies a path Path1 the assembly you are targeting is AssemblyName.dll, the CLR will locate the assembly in the following order
C:\AppDir\AssemblyName.dll
C:\AppDir\AssemblyName\AssemblyName.dll
C:\AppDir\Path1\AssemblyName.dll
C:\AppDir\Path1\AssemblyName\AssemblyName.dll
If the above method cannot find the assembly, a compilation error occurs, and if the assembly is loaded dynamically, an exception will be thrown at run time!
2,assembly.loadfrom ()
This method loads the assembly from the specified path, and when the method is actually called, the CLR opens the file, gets the assembly version, language culture, public key token, and so on, passes them to the Load method, and then the Load method uses the above policy to find the assembly. If an assembly is found, it is compared to the path specified in the LoadFrom method, and if the path is the same, the Assembly is considered part of the application, and if the path is different or the Load method does not find the assembly, the Assembly is simply loaded as a "data file". is not considered part of the application. This is why the load method mentioned in the 1th is more efficient than the LoadFrom method. In addition, because the assembly may be loaded as a "data file", loading the same assembly from different paths with LoadFrom causes a duplicate load. Of course, this method will load other assemblies referenced by this assembly.
3,assembly.loadfile ()
This method loads the assembly from the specified file and differs from the method above in that the method does not load other assemblies referenced by this assembly!
Conclusion: In general, you should choose the Load method to load the assembly, if you encounter the need to use the LoadFrom method, it is best to change the design and use the Load method instead!
Another: The difference between Assembly.loadfile and Assembly.LoadFrom
1, assembly.loadfile only load the corresponding DLL file, such as Assembly.loadfile ("Abc.dll"), then load Abc.dll, if Abc.dll is referenced def.dll, Def.dll will not be loaded.
Assembly.LoadFrom is not the same, it loads the DLL file and other DLLs it references, such as the example above, Def.dll will also be loaded.
2, when loading a assembly with Assembly.LoadFrom, will first check whether the front has been loaded with the same name assembly, such as Abc.dll has two versions (version 1 under directory 1, version 2 is placed under directory 2), the program was initially loaded in version 1, When loading version 2 o'clock with Assembly.LoadFrom ("2\\abc.dll"), it cannot be loaded, but instead returns version 1. Assembly.loadfile will not do such a check, such as the above example to Assembly.loadfile, then the correct loading version 2.
LoadFile: Loads the contents of the assembly file on the specified path. LoadFrom: Loads the contents of the assembly file based on the file name of the assembly.
Difference:
The LoadFile method is used to load and check assemblies that have the same identity but are located in different paths. However, the program's dependencies are not loaded.
LoadFrom cannot be used to load an assembly that identifies the same but has a different path.

Summarize:

Assembly.Load () method, Assembly.LoadFrom () method, difference of assembly.loadfile () method
In C #, we want to use reflection, first to understand the relationships of several classes in the following namespaces:
System.Reflection namespaces
(1) AppDomain: An application domain that can be understood as a logical container for a set of assemblies
(2) Assembly: assembly class
(3) Module: Modular class
(4) Type: The most core class for using reflection to get type information
There is a dependency between them, that is, an AppDomain can contain N assembly, a assembly can contain n module, and a module can contain n type.

1,assembly.load ()
This method loads the assembly through the long name of the assembly (including assembly name, version information, language culture, public key token), loads the other assemblies referenced by this assembly, and generally should take precedence over this method, which is much more efficient than LoadFrom. And does not cause the problem of repeated loading (the reason is explained on the 2nd)
With this method, the CLR applies a certain policy to find the assembly, in effect the CLR locates the Assembly in the following order:
⑴ If the assembly has a strong name, first look for the Assembly in the global Assembly Ease (GAC).
⑵ if the strong name of the assembly is not specified correctly or is not found in the GAC, the URL specified by the <codebase> element in the configuration file is searched for
⑶ If a strong name is not specified or cannot be found in the GAC, the CLR probes for a specific folder:
Assuming that your application directory is a privatepath in the c:\appdir,<probing> element that specifies a path Path1 the assembly you are targeting is AssemblyName.dll, the CLR will locate the assembly in the following order
C:\AppDir\AssemblyName.dll
C:\AppDir\AssemblyName\AssemblyName.dll
C:\AppDir\Path1\AssemblyName.dll
C:\AppDir\Path1\AssemblyName\AssemblyName.dll
If the above method cannot find the assembly, a compilation error occurs, and if the assembly is loaded dynamically, an exception will be thrown at run time!
2,assembly.loadfrom ()
This method loads the assembly from the specified path, and when the method is actually called, the CLR opens the file, gets the assembly version, language culture, public key token, and so on, passes them to the Load method, and then the Load method uses the above policy to find the assembly. If an assembly is found, it is compared to the path specified in the LoadFrom method, and if the path is the same, the Assembly is considered part of the application, and if the path is different or the Load method does not find the assembly, the Assembly is simply loaded as a "data file". is not considered part of the application. This is why the load method mentioned in the 1th is more efficient than the LoadFrom method. In addition, because the assembly may be loaded as a "data file", loading the same assembly from different paths with LoadFrom causes a duplicate load. Of course, this method will load other assemblies referenced by this assembly.
3,assembly.loadfile ()
This method loads the assembly from the specified file and differs from the method above in that the method does not load other assemblies referenced by this assembly!
Conclusion: In general, you should choose the Load method to load the assembly, if you encounter the need to use the LoadFrom method, it is best to change the design and use the Load method instead!
Another: The difference between Assembly.loadfile and Assembly.LoadFrom
1, assembly.loadfile only load the corresponding DLL file, such as Assembly.loadfile ("Abc.dll"), then load Abc.dll, if Abc.dll is referenced def.dll, Def.dll will not be loaded.
Assembly.LoadFrom is not the same, it loads the DLL file and other DLLs it references, such as the example above, Def.dll will also be loaded.
2, when loading a assembly with Assembly.LoadFrom, will first check whether the front has been loaded with the same name assembly, such as Abc.dll has two versions (version 1 under directory 1, version 2 is placed under directory 2), the program was initially loaded in version 1, When loading version 2 o'clock with Assembly.LoadFrom ("2\\abc.dll"), it cannot be loaded, but instead returns version 1. Assembly.loadfile will not do such a check, such as the above example to Assembly.loadfile, then the correct loading version 2.
LoadFile: Loads the contents of the assembly file on the specified path. LoadFrom: Loads the contents of the assembly file based on the file name of the assembly.
Difference:
The LoadFile method is used to load and check assemblies that have the same identity but are located in different paths. However, the program's dependencies are not loaded.
LoadFrom cannot be used to load an assembly that identifies the same but has a different path.

Transferred from: http://blog.csdn.net/lyncai/article/details/8621880

C # Reflection Assembly detailed description

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.