C # Reflection instance learning and attention content _ practical skills

Source: Internet
Author: User
Tags modifier reflection serialization static class
Getting Started with C # reflection first understand that C # reflection provides an object that encapsulates assemblies, modules, and types, and so on. So you can use reflection to dynamically create an instance of a type, bind a type to an existing object, or get a type from an existing object and call its methods or access its fields and properties. If you use attributes in your code, you can use reflection to access them.

MSDN Description
Reflection usually has the following uses:
Use Assembly to define and load assemblies, load modules that are listed in the assembly manifest, and find types from this assembly and create instances of that type.
Use module to discover the following information: The assembly that contains the module, and the classes in the module. You can also get all the global methods or other specific non-global methods that are defined on the module.
Use ConstructorInfo to discover the following information: the name of the constructor, parameters, access modifiers (such as public or private), and implementation details (such as abstract or virtual). Use the GetConstructors or GetConstructor method of Type to invoke a specific constructor.
Use MethodInfo to discover the following information: The name of the method, the return type, the parameter, the access modifier (such as public or private), and the implementation details (such as abstract or virtual). Use the GetMethods or GetMethod method of Type to invoke a particular method.
Use FieldInfo to discover the following information: The name of the field, the access modifier (such as public or private) and implementation details (such as static), and get or set the field value.
Use EventInfo to discover the following information: The name of the event, the event handler data type, the custom attribute, the declaring type and the reflection type, and so on, and add or remove an event handler.
Use PropertyInfo to discover the following information: The name of the property, the data type, the declaring type, the reflection type and the read-only or writable state, and get or set the property value.
Use ParameterInfo to discover the following information: The name of the parameter, the 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 are working in the reflection-only context of an application domain, use CustomAttributeData to learn about custom attributes. With CustomAttributeData, you can check them without creating an instance of the property.
Classes in System.Reflection.Emit namespaces provide a special form of reflection that enables you to generate types at run time.
Reflection can also be used to create an application called a type browser, which enables the user to select a type and then view information about the selected type.
There are other uses for reflection. Language compilers such as JScript use reflection to construct symbol tables. The classes in the System.Runtime.Serialization namespace use reflection to access the data and determine which fields to persist. The classes in the System.Runtime.Remoting namespace use reflection indirectly through serialization.

one of the simplest examples of C # reflection, first write the class library as follows
Copy Code code 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");
}
}
}

Compile with the command line compile csc/t:library ReflectTest.cs command to generate the ReflectTest.dll library file.
The following procedures are then written:
Copy Code code 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 is 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 # Reflection learning time points of attention
1. Specifies that the class library file must use an absolute path and cannot use a relative path (in fact it feels a little unreasonable and inconvenient)
2. 19 lines, the names of namespaces and classes must be specified together
3. In Example 1 you must instantiate a class that reflects reflection, because the method you want to use is not a static method.
4. Since this method has two parameters, you can specify the parameter using this Object method or directly write Method.invoke (obj, new object[] {"Test", 1});
5. In the example 2 we want to use the method is a static method, this time invoke, for the first parameter is ignored, that is, we write nothing will be called, even if we casually new an any such object, of course, this writing is not recommended. But corresponding to the example 1 if we use an instance of type inconsistency when we invoke, it will result in a run-time error.
6. The third example is a call to an example of a parameterless static method, at which point we do not need to specify two parameters, with null.

Again, if the class being invoked is a static class, need to pay attention to a problem, sure we will think of a problem, static class is not instantiated, at this time, 31 rows of class instantiation method We do not need, direct use invoke can be implemented, otherwise there will be run-time errors, In the same way, the first argument will be ignored, as long as we pass the right arguments.
C # reflection and the relevant content of C # reflection instances to introduce you here 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.