[C #] C # Reflection Analysis

Source: Internet
Author: User

C # Reflection Analysis

First, understand the concept of C # reflection. Reflection is a process of discovering the Runtime Library type. Reflection can be used to obtain a list of all types contained in a given assembly,
This list includes methods, fields, attributes, and events defined in a given type. You can also dynamically discover the excuses supported by a group of given classes, the parameters of methods, and other
Related information, such as the base class, namespace, and data list.

C # reflection namespace details:

1. Various types in the system. Reflection namespace

(1) An assembly can be used to load, understand, and manipulate an assembly.

(2) assemblyname can be used to find a large amount of information hidden in the Assembly's identity, such as version information and region information.

(3) eventinfo event information

(4) Information of the fieldinfo Field

(5) Information about the methodinfo Method

(6) parameterinfo parameter information

(7) propertyinfo attributes

(8) memberinfo is an abstract base class that defines public behaviors for eventinfo, fieldinfo, methodinfo, propertyinfo, and other types.

(9) module is used to access a given module with multi-file assembly

2. system. Type class

System. Type supports the following types of members:

(1) is *** is used to check a type of metadata, such as isabstract, isclass, and isvaluetype.

(2) Get *** is used to get a specified project from the type, such as getevent () to get a specified event of the type (eventinfo ).
In addition, each of these methods has a singular version and a plural version. For example, getevent () corresponds to a plural version of getevents (),
This method returns a related eventinfo array.

(3) findmembers () returns an array of the memberinfo type based on the query conditions.

(4) GetType () This static method returns a type instance based on a string name

(5) invokemember () binds a specified project to a later stage.

3. Three methods for obtaining a type instance

Because type is an abstract class, you cannot directly use the new keyword to create a type object.

(1) Use System. Object. GetType ()

Person Pe = new person (); // --------- defines PE as an object of the person class.
Type T = PE. GetType ();

(2) Use the system. type. GetType () static method. The parameter is a fully qualified name of the type.

Type T = type. GetType ("entity. person"); this method is overloaded. You can specify two Boolean parameters. One is used to control whether an exception is thrown when the current type cannot be found,

The other is used to indicate whether the string is case sensitive.

Type T = type. getType ("entity. person ", false, true); note that the input string does not contain the assembly information of the type. In this case, the type is considered to be defined in the currently executed assembly.

To obtain the type metadata of an external private assembly, the string parameter must use the type fully qualified name and the friendly name of the Assembly where the type is located.

Type T = type. getType ("entity. person "," entity "); // ------" entity "is the friendly name nested type of the type assembly. The incoming string can specify a + tag to indicate a nested type,

To obtain the type information of an enumeration type city nested in the person class, you can

Type T = type. GetType ("entity. Person + city ");

(3) Use the typeof Operator

Type T = typeof (person); comparison of the three methods:

To use the first method, you must first create an instance. However, when using the typeof operator, you still need to know the compilation information of the type,

The system. type. GetType () static method does not need to know the compilation information of the type, so it is the preferred method.

For the simplest C # reflection instance, first write the class library as follows:
Namespace reflectiontest
{
Public class writetest
{
// Public method with Parameters
Public void writestring (string S, int I)
{
Console. writeline ("writestring:" + S + I. tostring ());
}
// Static method with one parameter
Public static void staticwritestring (string S)
{
Console. writeline ("staticwritestring:" + S );
}
// Static method without Parameters
Public static void noneparawritestring ()
{
Console. writeline ("noparawritestring ");
}
}
}

Class testapp
{
Public static void main ()
{
Assembly ass;
Type type;
Object OBJ;
// Used to test the static method
Object any = new object ();
// The absolute path must be used for the specified class library file, and the relative path cannot be used.
Ass = assembly. LoadFile (@ "D: \ source CoDe \ 00.c# sudy \ 01. Reflection \ 01 \ reflecttest. dll ");
// The namespace and class names must be specified together.
Type = ass. GetType ("reflectiontest. writetest ");

/** // * Example1 ---------*/
Methodinfo method = type. getmethod ("writestring ");
String test = "test ";
Int I = 1;
Object [] parametors = new object [] {test, I };
// In the example, the class to be reflected must be instantiated because the method to be used is not a static method.
// Create an object instance
OBJ = ass. createinstance ("reflectiontest. writetest ");
// Execute the public method with Parameters
Method. Invoke (OBJ, parametors );
// Method. Invoke (any, parametors); // exception: the class to be reflected must be instantiated because the method to be used is not a static method.

/** // * Example2 ----------*/
Method = type. getmethod ("staticwritestring ");
Method. Invoke (null, new string [] {"test"}); // ignore the first parameter
// The first parameter is ignored, that is, nothing is called,
// Even if we create an object like any, this method is not recommended.
// However, if an instance of different types is used as the parameter in the example, a runtime error will occur.
Method. Invoke (OBJ, new string [] {"test "});
Method. Invoke (any, new string [] {"test "});

/** // * Example3 -----------*/
Method = type. getmethod ("noneparawritestring"); // call an example of a static method without parameters. In this case, we do not need to specify either of the two parameters. Use null. S
Method. Invoke (null, null );
}
}

From the above summary, we can see that for the dynamic library application reflection of external calls, assembly. LoadFile () is used, and then the get type and execution method are used;
When you use reflection to create an object instance in the current Assembly or execute a static method under a class, you only need to use type. GetType ("full name of the class ").

 

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.