Reflection in .NET Getting Started

xiaoxiao2021-03-06  55

MSDN: ms-help: //ms.vscc.2003/ms.msdnqtr.2003feb.2052/cpguide/html/cpcondiscoveringTypeinformationTruntime.htm Outline: 1, what is reflex 2, namespace and assembly of accessories 3, What type of information is used 4, how to use the reflection acquisition type 5, how to create an object 6 according to the type, how to obtain methods, and dynamic calling methods 7, dynamically create delegates

1, what is reflecting reflection, Chinese translation as a reflection. This is the way to get runtime type information in .NET, .NET's application consists of several parts: 'assembly (askEMBLY)', 'module (module)', the reflection provides one Methods of programming allow programmers to get information about these components in the program running period, for example:

The Assembly class can get the running assembly information, or dynamically load the assembly, and find the type information in the assembly and create an instance of this type. The Type class can get the type of object of the object, this information contains all the features of the object: method, constructor, attribute, etc., information, etc., can be obtained by Type class, and call it. MethodInfo contains information about the method, and the name, parameter, return value, etc. of the method can be obtained, and can be called. Such, as well as FieldInfo, EventInfo, etc., all of which are included under System.Reflection namespace.

2, the relationship between namespace and assembly, many people may still be very unclear about this concept, and it is necessary to clarify this. The namespace is similar to the Java package, but it is not completely equivalent, because Java packs must be placed according to the directory structure, and the namespace does not need.

The assembly is the minimum unit of the .NET application, compiled .dll, .exe is a fitting.

The relationship between the accessories and namespace is not one or one, nor does it contain each other, and one of the fittings can have multiple namespaces, and a namespace can also exist in multiple assemblies, which may be a bit blurred. : Accessories A: Namespace n1 {public class ac1 {...} public class ac2 {...}} namespace n2 {public class ac3 {...} public class ac4 {...}} installed accessories B: Namespace n1 {public class bc1 {...} Public Class BC2 {...}} namespace n2 {public class bc3 {...} public class bc4 {...}}

There are two namespaces of N1 and N2 in these two assemblies, and each declare two classes, which is complete, then we reference the accessories A in an application, then in this app, we It can be seen that the classes below the N1 are AC1 and AC2, N2, and the classes below are AC3 and AC4. Then we remove the reference to A, plus the reference to B, then we can see the following classes under this application to become BC1 and BC2, N2 below. If we simultaneously quote these two assemblies, then we can see four classes: AC1, AC2, BC1 and BC2.

Here, we can clear a concept, named space just explaining that a type is that family, such as someone is a Han nationality; someone is a Hui; the assembly indicates where a type lives, such as someone living in Beijing, some people live in Shanghai Then there is a Han people in Beijing, and there are Hui people. There are Han people in Shanghai, and there are also Hui people. This is not contradictory. Above we said that the accessories are a type of place, then use a class in a program, you must tell the compiler that this class lives, the compiler can find it, which means that the accessory must be referenced. So when you write a program, you may not be sure that this class is, just just knowing its name, can you use it? The answer is that this is reflected, which is the address of this type when the program is running, and find it. If you are interested, you will follow it.

3. If you get the type of information, you may have any questions. Since you can write a code during development, why still put it in the running period, not only cumbersome, and efficiency is also affected. This is the problem of seeing the heritability, just like the early binding and evening bindings, applied to different occasions. Some people have objected to evening bindings, the reason is the loss efficiency, but many people have not realized that he has used the evening binding when enjoying the benefits of the virtual function. This question says that it is not clear, so it is until it is. My opinion is that evening binding can bring a lot of design convenience, suitable use can greatly improve the reuse and flexibility of the program, but everything has two sides, when used, need to be measured again.

Then, what is the use of type information? Still give an example, many software developers like to leave some interfaces in their own software, others can write some plugins to expand the functionality of the software, such as I have a media player, I hope to expand it later. Identification, then I declare an interface: public interface {get;} decoder getDecoder ();} This interface contains an extension property, this property returns a supported extension, another method returns a decoder Object (here I assume a class of decoder, this class provides the ability to decode the file stream, the extension can be derived), and I can explain the file stream through the decoder object. Then I specify that all decoding plugins must be derived and implemented this interface, returns the decoder object in the getDecoder method, and configure the name of the type to my profile. In this case, I don't need to know the type of format in the future. I only need to get the type name of all decoders from the configuration file, and the dynamic creation of the media format is converted to IMEDIAFORMAT interface is used. This is a typical application of a reflection. 4. How to use the reflection acquisition type First we see how to get type information. There are two ways to get the type information, one is to get the instance object, I just get this instance object, the way to get this example may be an object of an Object, maybe an interface reference, but I don't know how it is. Type, I need to know, you can get the type object of instance objects by calling the method gettype declared on System.Object. For example, in a method, I need to judge whether the passing parameter implements an interface, if implemented A method for calling the interface: ... public void process (Object processobj) {type t = processsobj.gettype (); if (t.GetInterface ("iTest")! = Null) ...} ... another acquisition type The method is through Type.gettype and Assembly.gettype method, such as: type t = type.gettype ("system.string"); need to note, before we talked about the relationship between namespace and accessories, to find a class, It is necessary to specify its installation, or call GetType on the Assembly instance already obtained. The type of this package can write only the type name, and another exception is Mscorlib.dll. The type declared in this assembly can also omit the accessory name (when compiled by .NET assembly, the default is a reference to Mscorlib.dll, unless When compiling, specify it not to reference it), such as: system.string is declared in mscorlib.dll, the above Type T = Type.gettype ("System.String") is the correct system.data.DataTable is Sype.Data.DataTable ") can only get an empty reference in system.data.dll.

Must: TYPE T = Type.gettype ("System.Data.DataTable, System.Data, Version = 1.0.3300.0, Culture = NEUTRAL, PUBLICKEYTOKEN = B77A5C561934E089"); This can, everyone can look at the following post: http: / /EXPERT.9CBS.NET/EXPERT/topic/2210/2210762.xml?temp=.1919977 QQChen's answer is wonderful 5. How to dynamically create objects based on the type to dynamically create objects according to type, such as creation A DataTable:

Type t = type.gettype ("System.Data.DataTable, System.Data, Version = 1.0.3300.0, Culture = Neutral, Public, Public, PUBEYTOKEN = B77A5C561934E089");

DataTable Table = (DATATABLE) Activator.createInstance (T);

Example 2: Create an object Namespace TestSpace {public class testclass {private string_value = value;}}}}}}}}}}}}}}}}}}}. Object [] constructparms = new object [] {"hello"}; // constructor parameter TESTCLASS OBJ = (TESTCLASS) Activator.createInstance (t, constructparms); ... put parameters in order in the order of Object array 6 can be 6 How to get methods and dynamic calling methods Namespace testspace {public class testclass {private string _value; public testclass () {} public testclass () {_Value = value;

Public string getValue (string prefix) {if (_value == null) Return "null"; Else Return prefix ":" _Value;

Public string value {set {_value = value;} get {i (_value == null) Return "null"; else return_value;}}}}

The above is a simple class, including a parameter constructor, a getValue method, a value attribute, we can get the method and call it through the name of the method, such as:

// Get Type Information Type T = Type.getType ("Testspace.TestClass"); // Parameter Object [] constuctparms = new object [] {"{"}}; // Create Object Dobj = Activator .CreateInstance (t, constuctparms); // Get information information method method method ("getValue"); // Some flag bits of // Call the method, the meaning of this is public and an instance method, which is also the default value BindingFlags flag = BindingFlags.Public | BindingFlags.Instance; // GetValue method parameter object [] parameters = new object [] { "Hello"}; // call the method with an object receiving the return value object returnValue = method.Invoke ( DOBJ, FLAG, TYPE.DEFAULTBINDER, Parameters, NULL; the attribute and method call is different, you can also refer to MSDN

7. Dynamic creation entrustment is the basis of implementing events in C #, sometimes inevitable to create a delegation, actually a type: System.Delegate, all delegates are system.delegate from this class Some static methods are provided to dynamically create a delegate, such as a delegate:

namespace TestSpace {delegate string TestDelegate (string value); public class TestClass {public TestClass () {} public void GetValue (string value) {return value;}}} Example of use: TestClass obj = new TestClass (); // Get Type In fact, it can also be used directly to obtain type Type T = Type.gettype ("testspace.testclass"); // Create a proxy, incoming type, creating agent objects, and method name TestDelegate method = (testdelegate) delegate. CreateDelegate (T, Obj, "getValue);

String ReturnValue = Method ("Hello");

Here, we will simply tell the roles of reflection and some basic usage, there are many aspects that are not involved, interested friends can refer to MSDN. Very strange, many people don't want to watch MSDN, in fact, you want the answer, 99% can be found inside.

转载请注明原文地址:https://www.9cbs.com/read-114729.html

New Post(0)