C # reflection examples
1. Create a DLL for reflection.
Create a c # class library project, copy the Source Code below, compile and generate the DLL (if the DLL file name is testreflect. DLL)
1 using system;
2
3 namespace webtest
4 {
5/*** ///
6 // reflecttest abstract description.
7 //
8 public class reflecttest
9 {
10 public reflecttest ()
11 {}< br> 12
13 Public String writestring (string s)
14 {
15 return "Welcome," + S;
16}
17
18/*** //
19 // dsajkjflasjdfalksdjfaskfd
20 //
21 //
22 //
23 public static string writename (string S)
24 {
25 return "Welcome," + S;
26}
27
28 Public String writenopara ()
29 {
30 return "you are using a non-parameter method ";
31}
32}
33}
34
35
36
2. Example of reflection
Add the following functions to the ASPNET page:
1 Public void test1 ()
2 {
3 system. reflection. Assembly ass;
4 type;
5 object OBJ;
6 try
7 {
8 ass = system. reflection. Assembly. LoadFile (@ "D: \ testreflect. dll ");
9 type = ass. GetType ("webtest. reflecttest"); // The namespace and class name must be used.
10 system. reflection. methodinfo method = type. getmethod ("writestring"); // method name
11 OBJ = ass. createinstance ("webtest. reflecttest"); // The namespace and class name must be used.
12 string S = (string) method. Invoke (OBJ, new string [] {"jianglijun"}); // call an instance method
13
14 response. Write (S + "<br> ");
15 method = type. getmethod ("writename"); // method name
16 S = (string) method. Invoke (null, new string [] {"jianglijun"}); // call a static method
17 response. Write (S + "<br> ");
18
19 method = type. getmethod ("writenopara"); // No parameter instance method
20 s = (string) method. Invoke (OBJ, null );
21 response. Write (S + "<br> ");
22 method = NULL;
23}
24 catch (exception ex)
25 {
26 response. Write (Ex + "<br> ");
27}
28 finally
29 {
30 ass = NULL;
31 type = NULL;
32 OBJ = NULL;
33}
34}
35