C # basic reflection knowledge and practical application

Source: Internet
Author: User
Tags custom name

First, what is reflection?

Reflection provides encapsulated assembly, module, and type objects (type)

You can use reflection to dynamically create an instance of the type, bind the type to an existing object, or obtain the type from the existing object. Then, you can call the method of the type or access its fields and attributes.

In short, with reflection, many previously unfeasible functions can be implemented.

Here is a small example to show how reflection works:

Open vs2010, create a console application, and write code in program. CS.

First introduce the namespace:

using System.Reflection;

Run the following code:

         PropertyInfo len = typeof(string).GetProperty("Length");         string s = "Hello,reflection!";         int length = (int)len.GetValue(s, null);         Console.WriteLine(length.ToString());

Here, the Length attribute of string is obtained through reflection, and the attribute value is obtained by calling the getvalues method of propertyinfo. The prototype of the getvalues method is as follows:

public virtual object GetValue(object obj, object[] index);

The first parameter obj is an instance of the class that owns this attribute. In this example, the string S and S have the Length attribute.

The second parameter is the index value. Microsoft interprets it as follows:

Optional index values for indexed properties. This value shocould be null for non-indexed properties.

Generally, null is used. You can study it in depth.

The getvalues method returns the object type, so the conversion type must be mandatory.

 

The following is a method to obtain the string through reflection. The Code is as follows:

string s = "Hello,reflection!";MethodInfo method = typeof(string).GetMethod("Contains");bool result = (bool)method.Invoke(s, new object[] { "Hello" });Console.WriteLine(result);

The invoke method is defined as follows:

public object Invoke(object obj, object[] parameters);

This is easy to understand. The first parameter is the instance of the class that owns this method, or the string instance S.

The second parameter is the parameter of an object array.

Here, the contains method in string is called to determine whether the string contains a certain string.

 

The following code instantiates a String object through reflection:

     Type t = Type.GetType("System.String");         char[] para = new char[] { ‘H‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘ };         var o = Activator.CreateInstance(t, para);         Console.WriteLine(o);

This is similar to the get method. The only difference is that the string constructor parameter is a char [] array, so it must be of the correct type. Here, a string is instantiated and the value is hello.

 

As you can see, you have a preliminary understanding of reflection and will start to use it in practice:

Right-click the solution, add a project, select a class library, enter a name, and add a class library.

Add the custom class to the class library. The Code is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ReflectionDll{   public class Custom    {      public string Name { get; set; }      public string Address { get;set; }      public int Age { get; set; }      public DateTime BirthDay { get; set; }      public string GetInfo(string name = "",int age = 0)      {         if (name == "" && age == 0)         {            return "Custom Name: " + this.Name + ",Age: " + this.Age;         }         else         {            return "Custom Name: " + name + ",Age: " + age;         }      }   }}

Only several attributes and a method are declared for demonstration. Compile the library and add the reference class library in the console project (for convenience, otherwise, you must manually copy the DLL to the console project for each compilation ), in this way, Vs will automatically copy the generated DLL to the DEBUG directory on the console for convenient calling. The following code starts to use reflection to load the DLL:

        string path = Environment.CurrentDirectory + "\\ReflectionDll.dll";         Assembly assem = Assembly.LoadFile(path);         Type customType = assem.GetType("ReflectionDll.Custom");         var custom = Activator.CreateInstance(customType);

Note that the physical path of the DLL needs to be obtained first, so it doesn't matter whether or not to add the reference above. After the path is available, load the DLL using the LoadFile method of assembly and obtain the type of the class. Note that the parameters in the GetType method must be the full name of the class and namespace + class name, otherwise, it cannot be found.

In the last row, an instance of the class is created and the type is object.

The following code gets all attributes of M:

 PropertyInfo[] propertys = customType.GetProperties();         Console.WriteLine("******************************");         foreach (PropertyInfo pro in propertys)         {            Console.WriteLine("PropertyName:" + pro.Name + "\n" +               "PropertyType:" + pro.PropertyType + "\n" +               "ClassName:" + pro.ReflectedType + "\n" +               "DLLName:" + pro.Module + "\n");         }         Console.WriteLine("******************************");

Call the getproperties method to obtain all attributes, save them to the propertyinfo [] array, and traverse the output attribute values of the array.

The meanings of each attribute are as follows:

Name attribute name

Propertytype

Namecontrol + Class Name of the class in which reflectedtype is located

DLL file name of the module

 

Set the value of an attribute as follows:

     PropertyInfo p = customType.GetProperty("Name");     p.SetValue(custom, "CustomName",null);

Is it easy...

The following describes how to call the class method and some attributes. The Code is as follows:

Methodinfo _ method = customtype. getmethod ("getinfo"); // display the method name console. writeline ("INVOKE method:" + _ method. name); // display the returned data type console. writeline ("return type:" + _ method. returnparameter); parameterinfo [] parameters = _ method. getparameters (); foreach (parameterinfo Pa in parameters) {console. writeline (Pa. name + Pa. parametertype + Pa. position + Pa. member);} object [] paras = new object [] {"Jack", 24}; console. writeline (_ method. invoke (custom, paras ));
Like the property, parameters can be obtained through getparameters (). The obtained parameter information is as follows:

Name
Parametertype parameter data type
Position
All member output parameters

When calling a method with parameters, You need to input a parameter, a new object array, and write the parameters in order.


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.