C # Reflection

Source: Internet
Author: User

What is reflection, what is reflection capable of?

Reflection is:Type T1 = typeof (StringBuilder);

    • Instance type T2 = new StringBuilder (). GetType ();
    • static method by type class T3 = Type.GetType ("System.IO.Stream");

Regardless of the type of use, we end up with the same results.

So what information can we get through type?

Gets the type itself information (namespace name, full name, whether it is abstract, whether it is a class 、、、, and so on)
var T1 =typeof(StringBuilder); Console.WriteLine ("" + T1. Namespace); Console.WriteLine ( " direct base type:  "+ T1. BaseType); Console.WriteLine ( " full name:  "+ T1. FullName); Console.WriteLine ( " is an abstract type:  "+ T1. IsAbstract); Console.WriteLine ( " is the class:  "+ T1. IsClass); // ..... Wait                 

typeof(Tclass);  var Mets = T1. GetMembers (); // gets all public members of type Object           foreach (in Mets) {Console.WriteLine ("" "":"+ // M.membertype is a member type}             

What are the types of members that MemberType can contain? such as:(can oneself can F12 go inside to see)

Note: The MemberInfo property declaringtype returns the type defined by this property, and ReflectedType returns the object type that gets the property.

Such as:

Type T2 =typeof(Tclass);var Mets =T2. GetMembers ();Get all public members (the return value is a collection of memberinfo types)foreach (var m in Mets) { if (m.name=="Equals") {Console.WriteLine ("" "+ M . Membertype.tostring () + "":"+ m.name); // M.membertype is a member type

M.declaringtype;//gets the class that declares the member
M.reflectedtype;//gets the class object used to get this instance of MemberInfo.
} }

In T2, we know that this method is defined in the objec, called in Tclass, so:

We find that most of the members that get the type object are in Isxxx, Getxxx, GETXXXS format.

The isxxx format is basically to determine whether it is a certain type.

Both GetXXX and Getxxxs are put back into a type and a collection of types. The main types are:

FieldInfo encapsulates all information about a field   (via the GetFields or GetField method of the Tyep object)
The PropertyInfo type, which encapsulates the property information of the type, (via the type object's GetProperties or GetProperty method)
The constructorinfo type, which encapsulates the constructor information of the type; )
The MethodInfo type, which encapsulates the method information of the type;

MemberInfo type, which encapsulates all public members of a type, (* * is the GetMembers method we said above * *)
EventInfo type, which encapsulates the type of event information;
The parameterinfo type, which encapsulates the parameter information for methods and constructors;

They are all in the System.Reflection namespace, each of its isxxx, Getxxx, Getxxxs Details instance usage is not demonstrated. There is little difference between the GetMembers usage and the above.

Dynamic Call method

First define a class:

PublicClasstclass{Publicvoid Fun (string str) {Console.WriteLine ( " I'm the fun way, I'm called.  "+ str);} public void Fun2 () { Console.WriteLine ( " I am the Fun2 method, I was called.  ");} public static void< Span style= "color: #000000;" > Fun3 () {Console.WriteLine ( " I am fun3 static method, I was called  "); }} 
Call Mode One(call method using InvokeMember)

Invoking a parameter instance method fun

typeof(Tclass); T1. InvokeMember ("fun"test"}");     

Call the no-argument instance method fun2

typeof(Tclass); T1. InvokeMember ("fun2null");   

Calling a static method

typeof(Tclass); T1. InvokeMember ("fun3null");   

We have found a problem when we invoke an instance method, we need to pass the instance object past. ( Some people will say, all instances of the object, I also want you to live off the call a fart ah.) There is a case that after we have instantiated the object, it is still not certain that the method should be called when it can be used only. And then someone said, what if I'm not sure about the instance object? Then we will analyze the instance object is also dynamic. Then let's finish it and see. )

Let's say the meaning of these parameters.

First: The name of the method to be invoked dynamically.

The second: is an enumeration that indicates that a method is called

The third one: binder, which passes NULL, using the default value.

Fourth: Passed as an instance object ( when invoking an instance method) or a type object ( when a static method is called).

Fifth: An array of arguments to be passed to the called send.

Call Mode Two(call method using Methodinfo.invoke)
Type T1 =typeof(Tclass); T1. GetMethod ("funnew Tclass (), new string["{" testfun1< Span style= "color: #800000;" > "}); T1. GetMethod ( "fun2" BindingFlags.Instance | BindingFlags.Public). Invoke (new Tclass (), null ); T1. GetMethod ( "fun3" bindingflags.static | BindingFlags.Public). Invoke (T1, null);           

Use in fact and the above way a little difference.

True full-Dynamic invocation

In both of these ways, you always have to determine the known object name and method name when writing code. So can we call it when we don't know the object and the method name? The answer is yes, the implementation is as follows:

Console.WriteLine ("Please enter the object class name");String className =Console.ReadLine (); Console.WriteLine (" Please enter the method name to execute ");  String funname = console.readline (); Type T1 = Type.GetType (className); ConstructorInfo ci = T1. GetConstructors () [0]; // get constructor var obj = ci. Invoke (null);  instantiate the constructor T1. InvokeMember (Funname, BindingFlags.InvokeMethod, null, obj, null);       

Of course, this code can only be fun2, because the above-mentioned arguments are written dead. ( You can also make a little change, you can do fun, fun2, fun3)

The effect is as follows: ( object names and method names are entered manually)

Dynamically constructing objects

Let's define an object first:

Class tclass{public     tclass ()    {        Console.WriteLine (" constructor" was executed: "Publictclass (string str) {Console.WriteLine (" The " parameter constructor was executed. "+ str);}}            

Dynamically constructing objects

//Dynamically constructs an object, way one assembly ASM =Assembly.getexecutingassembly (); Tclass obj = (tclass) asm. CreateInstance ("Net.tclass",true);//true: Case insensitive//Dynamically constructs the object, in the way two objecthandle handler = Activator.CreateInstance (Null"Net. Tclass");//null: Current assembly obj = ( Tclass) handler. Unwrap (); // dynamically constructs an object, way three (constructs a parametric constructor) Assembly asm2 = assembly.getexecutingassembly (); obj = (tclass) asm2. CreateInstance ( "net.tclass true, Bindingflags.default, null, new string["{ Span style= "color: #800000;" > "testnull, null); //true: Case insensitive       

Perform:

Getting and modifying properties
var obj =NewTclass (); obj.name ="Tom"; Type type =typeof(Tclass);//Get Propertiesvar Name = type. InvokeMember ("Name", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,nullnew object[] {}) as string// Set the property type. InvokeMember ( "name" BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, nullnew object[] { New attribute (John Doe)  "}); Console.WriteLine (obj.name);              

Obtaining a type from an assembly gets the assembly where the current code is located(using getexecutingassembly)
Assembly-assembly.getexecutingassembly (); Console.WriteLine ("Current assembly name:" +ass. Manifestmodule.name); Console.WriteLine ("Current assembly path:" +ass. Location);

Loading assemblies by reflection and creating type objects in programs

From the assembly to obtain the type, this should be we usually use more. As we call dependency injection and inversion of control (this topic will be analyzed in the next blog post), it uses reflection to get the type from the assembly.

First, let's look at how to get the type from the assembly. We can use the static method provided by the assembly type LoadFrom () or load (), such as:

Assembly asm = Assembly.LoadFrom ("Demo.dll"); Assembly asm = assembly.load ("Demo");      

Difference:

Assembly asm = Assembly.LoadFrom ("Net.exe");//You need to add a suffix, you can specify the path, such as the following Assembly ASM1 = Assembly.LoadFrom (@"C:\01 file \05svn\blogscode\blogs\blogs.web\bin\blogs.bll.dll"); Assembly asm2 = Assembly.Load ("Blogs.bll "); // No suffix required, you cannot specify path //< Span style= "color: #008000;" >assembly ASM3 = Assembly.Load (@ "C:\01 file \05svn\blogscode\blogs\blogs.web\bin\blogs.bll"); // Here's an error // use load to load the assembly under the Bin directory row of the current program or the system assembly // here tclass can be an interface , then it can be implemented arbitrarily on the outside DLL. Tclass obj = (tclass) asm2. CreateInstance ( "net.tclass true); //true: Case-insensitive obj.fun (); *** call method in dynamically loaded DLL * * *          

This brings the functionality to be very powerful. We can also use an out-of-program assembly if we don't have a reference to the assembly. We can also refer to different assemblies depending on the situation. We can even configure which DLL the code should load, and which one in which DLL to run, by configuring the file directly. (the next article on the dependency injection will be talked about, students continue to pay attention to OH ~)

As we know from the above, reflection is not a certain probability, but a general designation of a class of operations. or a general designation of certain abilities. It feels bad to answer what the reflection is, only to say what reflection can do. It can dynamically create objects, dynamically invoke object methods, dynamically read and set properties and fields, and it can dynamically load DLLs outside the program. The general feeling is that most of them are related to " dynamics ".

C # Reflection

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.