C # reflection instance learning and attention

Source: Internet
Author: User

C # The first step to get started with reflection is to understand that C # reflection provides encapsulated assembly, module, and type objects. In this way, you can use reflection to dynamically create instances of the type, bind the type to an existing object, or obtain the type from the existing object and call its method or access its fields and properties. If attributes are used in the code, you can use reflection to access them.

MSDN description:
Reflection is usually used for the following purposes:
Use Assembly to define and load an Assembly, load the modules listed in the Assembly list, locate the type in this Assembly, and create instances of this type.
Use Module to discover the following information: including the Module assembly and classes in the Module. You can also obtain all global methods defined on the module or other specific non-Global methods.
Use ConstructorInfo to find the following information: name, parameter, access modifier (such as public or private) and implementation details (such as abstract or virtual) of the ConstructorInfo. Use the GetConstructors or GetConstructor method of Type to call a specific constructor.
You can use MethodInfo to find the following information: method name, return type, parameter, access modifier (such as public or private), and implementation details (such as abstract or virtual. Use the GetMethods or GetMethod method of Type to call a specific method.
Use FieldInfo to find the following information: field name, access modifier (such as public or private), implementation details (such as static), and so on; and obtain or set the field value.
Use EventInfo to find the following information: event name, event handler data type, custom attribute, declaration type, and reflection type, and add or remove event handlers.
Use PropertyInfo to find the following information: attribute name, data type, declaration type, reflection type, read-only or writable status, and get or set the attribute value.
You can use ParameterInfo to find the following information: Parameter Name, data type, whether the parameter is an input parameter or an output parameter, and the position of the parameter in the method signature.
When you work in only reflection context of an application domain, use CustomAttributeData to learn about custom attributes. With CustomAttributeData, you do not have to create Attribute instances to check them.
The System. Reflection. Emit namespace class provides a special form of Reflection that enables you to generate types at runtime.
Reflection can also be used to create an application called a type browser. It allows you to select a type and view information about the selected type.
Reflection has other functions. JScript and other language compilers use reflection to construct symbol tables. The classes in the System. Runtime. Serialization namespace use reflection to access data and determine the fields to be permanently saved. Classes in the System. Runtime. Remoting namespace indirectly use Reflection Through serialization.

For the simplest C # reflection instance, first write the class library as follows::
Copy codeThe Code is as follows:
Using System;
Namespace ReflectionTest
{
Public class WriteTest
{
// Public method with parametors
Public void WriteString (string s, int I)
{
Console. WriteLine ("WriteString:" + s + I. ToString ());
}
// Static method with only one parametor
Public static void StaticWriteString (string s)
{
Console. WriteLine ("StaticWriteString:" + s );
}
// Static method with no parametor
Public static void NoneParaWriteString ()
{
Console. WriteLine ("NoParaWriteString ");
}
}
}

Use the command line to compile the csc/t: library ReflectTest. cs command to generate the ReflectTest. dll library file.
Then write the following program:
Copy codeThe Code is as follows:
Using System;
Using System. Reflection;
Class TestApp
{
Public static void Main ()
{
Assembly ass;
Type type;
Object obj;
Object any = new Object ();
Ass = Assembly. LoadFile (@ "D: \ Source Code \ 00.C# Sudy \ 01. Reflection \ 01 \ ReflectTest. dll ");
Type = ass. GetType ("ReflectionTest. WriteTest ");
/* Example1 ---------*/
MethodInfo method = type. GetMethod ("WriteString ");
String test = "test ";
Int I = 1;
Object [] parametors = new Object [] {test, I };
Obj = ass. CreateInstance ("ReflectionTest. WriteTest ");
Method. Invoke (obj, // Instance object of the class need to be reflect
Parametors );
// Method. Invoke (any, parametors); // RuntimeError: class reference is wrong
/* Example2 ----------*/
Method = type. GetMethod ("StaticWriteString ");
Method. Invoke (null, new string [] {"test "});
Method. Invoke (obj, new string [] {"test "});
Method. Invoke (any, new string [] {"test "});
/* Example3 -----------*/
Method = type. GetMethod ("NoneParaWriteString ");
Method. Invoke (null, null );
}
}

C # Notes for reflection Learning:
1. the specified class library file must use an absolute path and cannot use a relative path (in fact, it seems a bit unreasonable and inconvenient)
Row 3: The namespace and class names must be specified together.
3. In example 1, the class to be reflected must be instantiated, because the method to be used is not a static method.
4. Because this method has two parameters, you can use this Object method to specify the parameter or directly write method. Invoke (obj, new Object [] {"test", 1 });
5. in Example 2, the method we want to use is a static method. In this case, when invoking, the first parameter is ignored, that is, nothing is called, even if we just create an Object like any, this method is not recommended. However, if an instance of different types is used as a parameter in the example, a runtime error will occur.
6. The third example is an example of calling a static method without parameters. At this time, we do not need to specify the two parameters. We can use null.

Another problem is that when the called class is a static class, you must pay attention to one problem. We will certainly think of a problem where the static class cannot be instantiated. At this time, we don't need to instantiate the 31 rows of classes. You can simply use Invoke to implement the method. Otherwise, a running error will occur. In the same way, the first parameter will be ignored, as long as we pass the correct parameter.
The C # reflection and C # reflection instance content will be introduced here. I hope to help you understand and learn C # reflection and C # reflection instance applications.

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.