反射

反射基本用法,取自MSDN,

 1using System;
 2using System.Reflection;
 3using System.Security.Permissions;
 4
 5[assembly:AssemblyVersionAttribute("1.0.2000.0")]
 6
 7public class Example
 8{
 9    private int factor;
10    public Example(int f)
11    {
12        factor = f;
13    }

14
15    public int SampleMethod(int x) 
16    
17        Console.WriteLine("\nExample.SampleMethod({0}) executes.", x);
18        return x * factor;
19    }

20
21    public static void Main()
22    {
23        Assembly assem = Assembly.GetExecutingAssembly();
24
25        Console.WriteLine("Assembly Full Name:");
26        Console.WriteLine(assem.FullName);
27
28        // The AssemblyName type can be used to parse the full name.
29        AssemblyName assemName = assem.GetName();
30        Console.WriteLine("\nName: {0}", assemName.Name);
31        Console.WriteLine("Version: {0}.{1}"
32            assemName.Version.Major, assemName.Version.Minor);
33
34        Console.WriteLine("\nAssembly CodeBase:");
35        Console.WriteLine(assem.CodeBase);
36
37        // Create an object from the assembly, passing in the correct number
38        // and type of arguments for the constructor.
39        Object o = assem.CreateInstance("Example"false
40            BindingFlags.ExactBinding, 
41            nullnew Object[] 2 }nullnull);
42
43        // Make a late-bound call to an instance method of the object.    
44        MethodInfo m = assem.GetType("Example").GetMethod("SampleMethod");
45        Object ret = m.Invoke(o, new Object[] 42 });
46        Console.WriteLine("SampleMethod returned {0}.", ret);
47
48        Console.WriteLine("\nAssembly entry point:");
49        Console.WriteLine(assem.EntryPoint);
50    }

51}

52
53/* This code example produces output similar to the following:
54
55Assembly Full Name:
56source, Version=1.0.2000.0, Culture=neutral, PublicKeyToken=null
57
58Name: source
59Version: 1.0
60
61Assembly CodeBase:
62file:///C:/sdtree/AssemblyClass/cs/source.exe
63
64Example.SampleMethod(42) executes.
65SampleMethod returned 84.
66
67Assembly entry point:
68Void Main()
69 */
posted on 2008-04-15 15:31  Eric huang  阅读(217)  评论(0编辑  收藏  举报