C # reflection instance

Source: Internet
Author: User

1. Create a DLL for reflection.

Create a C # class library project and copySource codeCompile and generate the DLL as follows (if the DLL file name is testreflect. dll)

1 Using System;
2
3 Namespace Webtest
4 {
5   /**/ /// <Summary>
6 ///Reflecttest abstract description.
7 /// </Summary>
8   Public   Class Reflecttest
9   {
10 Public Reflecttest ()
11 {}
12
13 Public   String Writestring ( String S)
14 {
15Return "Welcome," +S;
16}
17
18 /**/ ///   <Summary>
19 /// Dsajkjflasjdfalksdjfaskfd
20 ///   </Summary>
21 ///   <Param name = "S"> </param>
22 ///   <Returns> </returns>
23 Public   Static   String Writename ( String S)
24 {
25Return "Welcome," +S;
26}
27
28 Public   String Writenopara ()
29 {
30Return "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 type;
5 Object OBJ;
6 Try
7 {
8 Ass = System. reflection. Assembly. LoadFile ( @" D: \ testreflect. dll " );
9 Type = Ass. GetType ( " Webtest. reflecttest " ); // Must use namespace + class name
10 System. reflection. methodinfo Method = Type. getmethod ( " Writestring " ); // Method Name
11 OBJ = Ass. createinstance ( " Webtest. reflecttest " ); // Must use namespace + class name
12 String S = ( String ) Method. Invoke (OBJ, New   String [] {"Wahaha"} ); // Instance method call
13
14 Response. Write (S + " <Br> " );
15 Method = Type. getmethod ( " Writename " ); // Method Name
16 S = ( String ) Method. Invoke ( Null , New   String [] {"Wahaha "} ); // Call static methods
17 Response. Write (S + " <Br> " );
18
19 Method = Type. getmethod ( " Writenopara " ); // Example method without Parameters
20 S = ( String ) Method. Invoke (OBJ, Null );
21 Response. Write (S + " <Br> " );
22 Method =   Null ;
23 }
24 Catch (Exception ex)
25 {
26Response. 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.