C # Reflection Instance explanation

Source: Internet
Author: User

1 Creating a DLL for reflection use

Create a new C # class library project, copy the source code below, compile the build DLL (if the DLL's filename is TestReflect.dll)

1using System;
2
3namespace Webtest
4{
5 /**//// <summary>
6 /// ReflectTest 的摘要说明。
7 /// </summary>
8 public class ReflectTest
9 {
10 public ReflectTest()
11 {}
12
13 public string WriteString(string s)
14 {
15  return "欢迎您," + 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 {
25  return "欢迎您光临," + s;
26 }
27
28 public string WriteNoPara()
29 {
30  return "您使用的是无参数方法";
31 }
32 }
33}

2 Examples of applications applied to reflection

Add the following function to the ASPNET page:

1public 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 the namespace + class name
Ten System.Reflection.MethodInfo method = type. GetMethod ("writestring");//Method name
One obj = ass. CreateInstance ("Webtest.reflecttest");/must use the namespace + class name
A string s = (string) method. Invoke (obj,new string[]{"Jianglijun"}); The invocation of the instance method

Response.Write (s+ "<br>"), and
method = type. GetMethod ("Writename");//method name
S = (string) methods. Invoke (null,new string[]{"Jianglijun"}); The call to the static method
Response.Write (s+ "<br>");

methods = type. GetMethod ("Writenopara");//No parameter instance method
S = (string) methods. Invoke (Obj,null);
Response.Write (s+ "<br>");
method = null;
23}
catch (Exception ex)
{
Response.Write (ex+ "<br>");
27}
finally
{
ass = null;
-type = null;
= obj = null;
:
}
/ p>

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.