C # Reflection mechanism (RPM)

Source: Internet
Author: User
Tags mscorlib

1 What is reflection

2, the relationship between the name space and assembly parts

3. What is the use of type information during operation?

4. How to use reflection to get types

5. How to create objects dynamically based on type

6. How to get methods and dynamic call methods

7, dynamically create delegate
1, what is reflection         Reflection, Chinese translation is reflection.         this is. NET to get run-time type information. NET application consists of several parts: ' Assembly (Assembly) ', ' module ', ' type ', and reflection provides a programmatic way for programmers to obtain information about these components during the program's run time, for example:
  The       Assembly class can obtain running assembly information, load assemblies dynamically, and find type information in assemblies, and create instances of that type. The type class can obtain information about the types of objects that contain all of the elements of the object: Methods, constructors, properties, and so on, which can be obtained through the type class and called. MethodInfo contains information about the method through which the name, parameter, return value, etc. of the method can be obtained, and can be called. And so on, FieldInfo, EventInfo and so on, all of these classes are included under the System.Reflection namespace.
2, the relationship between namespaces and assemblies         Many people may still be very unclear about this concept, for qualifying. NET programmer, it is necessary to clarify this point.         namespaces are similar to java packages, but not exactly equivalent, because Java packages must be placed according to the directory structure, Namespaces are not required.
        assemblies are. NET application execution, the compiled. dll,. exe are assemblies.
        assembly and namespace relationships are not one by one and do not contain each other, a single assembly can have multiple namespaces, a namespace can also exist in multiple assemblies, which may be a bit vague, for example: assembly A:

    1. Namespace N1
    2. {
    3. public class AC1 {...}
    4. public class AC2 {...}
    5. }
    6. Namespace N2
    7. {
    8. public class AC3 {...}
    9. public class ac4{...}
    10. }
Copy Code

Fitting B:

    1. Namespace N1
    2. {
    3. public class BC1 {...}
    4. public class BC2 {...}
    5. }
    6. Namespace N2
    7. {
    8. public class BC3 {...}
    9. public class bc4{...}
    10. }
Copy Code

Both of the two assemblies have N1 and N2 two namespaces, and each declares two classes, which is perfectly possible, and then we reference assembly A in an application, so in this application we can see N1 the following classes for AC1 and ac2,n2 are AC3 and AC4.         Then we get rid of the reference to a, plus a reference to B, then we can see under this application N1 the following classes become BC1 and BC2,N2. If we refer to both assemblies at the same time, we can see four classes below N1: AC1, AC2, BC1, and BC2.
Here, we can clear a concept, the namespace only shows that a type is the family, for example, some people are Han, some people are Hui, while the assembly shows where a type of living, such as people living in Beijing, some people live in Shanghai, then there are Han Chinese people in Beijing, there are Hui people, Shanghai Han people, also have Hui people, This is not contradictory.
As we said, the assembly is a type of place to live, so in a program to use a class, you have to tell the compiler where the class lives, the compiler can find it, that is, the assembly must be referenced. So if you're writing a program, maybe you're not sure where the class is, just know its name and you can't use it? The answer is yes, this is reflection, is to provide the type of address when the program is running, and to find it. If you are interested, then look down.
3. What is the use of type information during operation?Some people may wonder, since the development can write good code, why still put in the run time to do, not only cumbersome, and efficiency is also affected. This is a matter of opinion, as early binding and late binding, applied to different occasions. Some people oppose late binding, the reason is the loss of efficiency, but many people in the enjoyment of the benefits of virtual function is not aware that he has been used late binding.         The problem is not few words to be clear, so it is donuts. My view is that late binding can bring a lot of design convenience, the appropriate use can greatly improve the reusability and flexibility of the program, but everything has two sides, the use of time, it needs to be measured repeatedly.
Then, what is the use of type information at run time? As an example, many software developers prefer to leave some of their softwareinterface, other people can write some plug-ins to expand the functionality of the software, such as I have a media player, I hope that in the future can be easily extended to identify the format, then I declare an interface:

    1. public interface Imediaformat
    2. {
    3. String Extension {get;}
    4. Decoder Getdecoder ();
    5. }
Copy Code

This interface contains a extension attribute, This property returns the supported extension, and another method returns the object of a decoder (here I assume a decoder class that provides the ability to decode the file stream, which the extension can derive from), and I can interpret the file stream through the decoder object. Then I'm going to rule that all the decoding plugins must derive a decoder, implement this interface, return the decoder object in the Getdecoder method, and configure the name of its type This is a typical application of reflection.
4, how to use reflection to get types         First we look at how to get type information.         There are two ways to get type information, one is to get an instance object         This time I just get this instance object, the way I get it is probably a reference to an object, Maybe it's a reference to an interface, but I don't know the exact type, I need to know, Then you can get the type object of the instance object by calling the method GetType declared on System.Object, such as in a method, I need to determine whether the passed in parameter implements an interface, and if so, one method of calling the interface:

    1. ...
    2. public void Process (object processobj)
    3. {
    4. Type t = Processsobj.gettype ();
    5. if (T.getinterface ("ITest")!=null)
    6. ...
    7. }
    8. ...
Copy Code

Another way to get types is through Type.GetType and Assembly.GetType methods, such as:               type  t  =& nbsp Type.GetType ("System.String");         It's important to note that before we talk about namespaces and assembly relationships, to find a class, you must specify the assembly in which it is located, or call GetType on the assembly instance that you have already obtained.         types in this assembly can write only type names, Another exception is mscorlib.dll, the type declared in this assembly can also omit the assembly name (when the. NET assembly is compiled by default, the mscorlib.dll is referenced, unless it is explicitly specified at compile time), such as:           System.String is declared in mscorlib.dll, the above type  t  =  type.gettype ("System.String") is correct           System.Data.DataTable is declared in System.Data.dll, then: Type.GetType (" System.Data.DataTable ") will only be given a null reference.           must: type  t  =  Type.GetType ("System.data.datatable,system.data, version=1.0.3300.0,  culture=neutral,  publickeytoken=b77a5c561934e089 ");           This way, you can see this post:                 Http://exper T.csdn.net/expert/to ... 2.xml?temp=.1919977           Qqchen the answer is wonderful.
5. How to create objects dynamically based on typeSystem.activator provides a way to dynamically create objects based on types, such as creating a DataTable:

    1. Type t = Type.GetType ("system.data.datatable,system.data,version=1.0.3300.0, Culture=neutral, PublicKeyToken= b77a5c561934e089 ");
    2. DataTable table = (DataTable) activator.createinstance (t);
Copy Code

Example two: Creating an object from an argument-based constructor

    1. Namespace Testspace
    2. {
    3. public class TestClass
    4. {
    5. private string _value;
    6. Public TestClass (String value)
    7. {
    8. _value=value;
    9. }
    10. }
    11. }
    12. ...
    13. Type t = Type.GetType ("Testspace.testclass");
    14. object[] constructparms = new object[] {"Hello"}; Constructor parameters
    15. TestClass obj = (testclass) activator.createinstance (t,constructparms);
    16. ...
Copy Code

Put the parameters in an object array in order
6. How to get methods and dynamic call methods

  1. Namespace Testspace
  2. {
  3. public class TestClass {
  4. private string _value;
  5. Public TestClass () {
  6. }
  7. Public TestClass (string value) {
  8. _value = value;
  9. }
  10. public string GetValue (string prefix) {
  11. if (_value==null)
  12. return "NULL";
  13. Else
  14. Return prefix+ ":" +_value;
  15. }
  16. public string Value {
  17. set {
  18. _value=value;
  19. }
  20. get {
  21. if (_value==null)
  22. return "NULL";
  23. Else
  24. return _value;
  25. }
  26. }
  27. }
  28. }
Copy Code

above is a simple class , which contains a parameterized constructor, a GetValue method, a Value property, we can get the method by the name of the method and call it, for example:

    1. Get type information
    2. Type t = Type.GetType ("Testspace.testclass");
    3. Parameters of the constructor
    4. object[] constuctparms = new object[]{"Timmy"};
    5. To create an object from a type
    6. Object dobj = Activator.CreateInstance (t,constuctparms);
    7. Get information about a method
    8. MethodInfo method = T.getmethod ("GetValue");
    9. Some flag bits of the calling method, meaning public and instance methods, which are the default values
    10. BindingFlags flag = BindingFlags.Public | BindingFlags.Instance;
    11. Parameters of the GetValue method
    12. object[] Parameters = new object[]{"Hello"};
    13. Invokes a method that receives a return value with an object
    14. Object returnvalue = method. Invoke (Dobj,flag,type.defaultbinder,parameters,null);
Copy Code

properties are similar to method calls , you can also refer to MSDN
7, dynamically create a delegate         delegate is the basis for implementing events in c#, Sometimes it is unavoidable to create a delegate dynamically, in fact the delegate is also a type: System.Delegate, all delegates are derived from this class         System.Delegate provides a number of static methods to dynamically create a delegate, such as a delegate:

    1. Namespace Testspace {
    2. Delegate string Testdelegate (string value);
    3. public class TestClass {
    4. Public TestClass () {
    5. }
    6. public void GetValue (string value) {
    7. return value;
    8. }
    9. }
    10. }
Copy Code

Examples of Use:

    1. TestClass obj = new TestClass ();
    2. To get the type, you can actually get the type directly with TypeOf.
    3. Type t = Type.GetType ("Testspace.testclass");
    4. Create proxies, incoming types, objects that create proxies, and method names
    5. Testdelegate method = (testdelegate) delegate.createdelegate (t,obj, "GetValue");
    6. String ReturnValue = Method ("Hello");
Copy Code

C # Reflection mechanism (RPM)

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.