C # Reflection Assembly specific Instructions

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 useful example, reflect the method in the DLL

Reflection is the process by which an assembly is discovered and executed, and the information inside an assembly, such as *.exe or *.dll, can be obtained by reflection. You can use reflection to see the interfaces, classes, methods, fields, properties, attributes, and so on within an assembly. In the System.Reflection namespace, including multiple reflection-frequently used classes, the following table lists several classes that are used frequently.
Type action
Assembly uses this class to load manipulate an assembly and obtain 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 enables 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
By Assembly the ability to dynamically load assemblies and view the internal information of an assembly, the most frequently used method is load ().
Assembly assembly=assembly.load ("myassembly");
Use the Assembly Object CreateInstance (String) method to reflect the creation of an object, with a class name of 0.
Second, System.Type class
Type is the most frequently used class, which allows the internal information of a class to be obtained through type, and it can be reflected to create an object. There are generally three commonly used methods to obtain 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 the 0 is the class name, and the number of 1 indicates whether the exception is thrown if the corresponding class is not found, and 1 indicates whether the class name distinguishes between uppercase and lowercase
Examples:
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

Type type=typeof (Example);    Methodinfo[] Listmethodinfo=type. GetMethods ();    foreach (MethodInfo MethodInfo in Listmethodinfo)         cosole.writeline ("Method name is" +methodinfo.name);


2. We can also run Method 2 in the class through the reflection method. We can also run the method inside the class by means of the reflection method.

Assembly assembly= assembly.load ("myassembly");   Type type=assembly. GetType ("Example");   Object Obj=activator.createinstance (type);   MethodInfo Methodinfo=type. GetMethod ("Hello World");  Gets the MethodInfo object   methodinfo.invoke (obj,null) According to the method name;  The reference 1 type is object[], which represents the corresponding parameter of the Hello World method, and the input value is null to indicate no parameters


Iv. Reflection Properties
1. You can find the properties within the class by System.Reflection.PropertyInfo
Frequently used methods have 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
Frequently used methods have 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
Frequently used methods have GetValue (object,object[]) Get property values and SetValue (object,object,object[]) Set property values

Type type=typeof (Example);    Propertyinfo[] Listpropertyinfo=type. GetProperties ();    foreach (PropertyInfo PropertyInfo in Listpropertyinfo)         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

 Assembly assembly=assembly.load ("myassembly"); Type type=assembly.   GetType ("Example");   Object Obj=activator.createinstance (type); PropertyInfo Propertyinfo=obj.    GetProperty ("Name");                Gets the Name Property object var name=propertyinfo.getvalue (obj,null); Gets the value of the Name property PropertyInfo Propertyinfo2=obj.     GetProperty ("Age");                              Gets the Age Property object 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 contains two frequent usages SetValue (object, Object) and GetValue (object) because the usage is very similar to the Reflection property, which is no longer introduced 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 the entire characteristics of a class
V. Reflection fields
The fields within the class can be found by System.Reflection.FieldInfo
It contains two frequent usages SetValue (object, Object) and GetValue (object) because the usage is very similar to the Reflection property, which is no longer introduced 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 the entire characteristics of a class

Type type=typeof ("Example");   Object[] Typeattributes=type. GetCustomAttributes (false);       Gets the attributes of the example Class   foreach (object attribute in TypeAttributes)         Console.WriteLine ("Attributes description is" + Attribute. ToString ());


The following example enables you to get all the properties of the example class Name property by using the following sample to get all the properties of the example class Name property

public class Example   {         [DataMemberAttribute]         publics string Name          {get;set;}        ..................    }    Type type = typeof (Example);            PropertyInfo Propertyinfo=type. GetProperty ("Name");    Gets the Name property of the example class,    foreach (object attribute in Propertyinfo.getcustomattributes (false))        //Traverse all attributes of the Name property           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 of all to figure out the relationships of several classes in the following namespaces:
System.Reflection namespaces
(1) AppDomain: An application domain that can interpret it 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
They are a kind of subordination, that is to say, an AppDomain can include N assembly, a assembly can include n module, and a module can include n type.

1,assembly.load ()
This method loads the assembly by its long name (which contains the assembly name, version number information, language culture, public key token), and loads the other assemblies referenced by this assembly, which should normally be used preferentially, and is much more efficient than LoadFrom. And does not cause repeated loading problems (reasons explained in 2nd)
With this approach, the CLR applies a certain policy to find the Assembly, and in fact the CLR locates the Assembly in the following order, for example:
⑴ assumes that the assembly has a strong name, and first finds 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 detects a specific directory:
If your application folder is a privatepath in the c:\appdir,<probing> element that specifies a path Path1, the assembly that you want to locate is AssemblyName.dll, the CLR will locate the assembly in the following order, for example:
C:\AppDir\AssemblyName.dll
C:\AppDir\AssemblyName\AssemblyName.dll
C:\AppDir\Path1\AssemblyName.dll
C:\AppDir\Path1\AssemblyName\AssemblyName.dll
Assuming that the above method cannot find the assembly, a compilation error occurs, assuming that the assembly is loaded dynamically and throws an exception at execution time!
2,assembly.loadfrom ()
This method loads the assembly from the specified path, in effect the CLR opens the file, gets the assembly version number, language culture, public key token, and so on, and passes them to the Load method, and then the Load method uses the above policy to find the assembly. Assuming the assembly is found, it is compared to the path specified in the LoadFrom method, assuming that the Assembly is considered part of the application, assuming that 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", using LoadFrom to load the same assembly from a different path can result in repeated loading. This method, of course, loads other assemblies referenced by this assembly.
3,assembly.loadfile ()
This method loads the assembly from the specified file, unlike the method above, where this 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 replace with the Load Method!
Another: The difference between Assembly.loadfile and Assembly.LoadFrom
1, assembly.loadfile only load the corresponding DLL file, for example, 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, load a assembly with Assembly.LoadFrom, will first check whether the front has already loaded the same name assembly, For example, Abc.dll has two version number (version number 1 under folder 1, version number 2 under folder 2), the program starts with the version number 1 loaded, when the use of Assembly.LoadFrom ("2\\abc.dll") load version number 2 o'clock, cannot be loaded, but return version number 1. Assembly.loadfile will not do this kind of inspection, for example, the above example replaced with Assembly.loadfile, then the version number 2 can be loaded correctly.
LoadFile: Loads the contents of the assembly file on the specified path. LoadFrom: Loads the contents of the assembly file according to 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 has the same identity but a different path.

Summarize:

Assembly.Load () method, Assembly.LoadFrom () method, difference of assembly.loadfile () method
In C #, we want to use reflection, first of all to figure out the relationships of several classes in the following namespaces:
System.Reflection namespaces
(1) AppDomain: An application domain that can interpret it 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
They are a kind of subordination, that is to say, an AppDomain can include N assembly, a assembly can include n module, and a module can include n type.

1,assembly.load ()
This method loads the assembly by its long name (which contains the assembly name, version number information, language culture, public key token), and loads the other assemblies referenced by this assembly, which should normally be used preferentially, and is much more efficient than LoadFrom. And does not cause repeated loading problems (reasons explained in 2nd)
With this approach, the CLR applies a certain policy to find the Assembly, and in fact the CLR locates the Assembly in the following order, for example:
⑴ assumes that the assembly has a strong name, and first finds 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 detects a specific directory:
If your application folder is a privatepath in the c:\appdir,<probing> element that specifies a path Path1, the assembly that you want to locate is AssemblyName.dll, the CLR will locate the assembly in the following order, for example:
C:\AppDir\AssemblyName.dll
C:\AppDir\AssemblyName\AssemblyName.dll
C:\AppDir\Path1\AssemblyName.dll
C:\AppDir\Path1\AssemblyName\AssemblyName.dll
Assuming that the above method cannot find the assembly, a compilation error occurs, assuming that the assembly is loaded dynamically and throws an exception at execution time!
2,assembly.loadfrom ()
This method loads the assembly from the specified path, in effect the CLR opens the file, gets the assembly version number, language culture, public key token, and so on, and passes them to the Load method, and then the Load method uses the above policy to find the assembly. Assuming the assembly is found, it is compared to the path specified in the LoadFrom method, assuming that the Assembly is considered part of the application, assuming that 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", using LoadFrom to load the same assembly from a different path can result in repeated loading. This method, of course, loads other assemblies referenced by this assembly.
3,assembly.loadfile ()
This method loads the assembly from the specified file, unlike the method above, where this 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 replace with the Load Method!
Another: The difference between Assembly.loadfile and Assembly.LoadFrom
1, assembly.loadfile only load the corresponding DLL file, for example, 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, load a assembly with Assembly.LoadFrom, will first check whether the front has already loaded the same name assembly, For example, Abc.dll has two version number (version number 1 under folder 1, version number 2 under folder 2), the program starts with the version number 1 loaded, when the use of Assembly.LoadFrom ("2\\abc.dll") load version number 2 o'clock, cannot be loaded, but return version number 1. Assembly.loadfile will not do this kind of inspection, for example, the above example replaced with Assembly.loadfile, then the version number 2 can be loaded correctly.
LoadFile: Loads the contents of the assembly file on the specified path. LoadFrom: Loads the contents of the assembly file according to 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 has the same identity but a different path.

C # Reflection Assembly specific Instructions

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.