C # reflection examples

Source: Internet
Author: User

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

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.