首页 > 代码库 > 第15章 .NET中的反射

第15章 .NET中的反射

技术分享
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Reflection;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            //TestClass.ShowMsg();            //TestClass.ShowMsg(new Message());            //Assembly asm = Assembly.GetExecutingAssembly();            //Object obj=asm.CreateInstance("ConsoleApplication2.Calculator",true);            //Calculator cal=(Calculator)obj;            //Object[] parameters = new Object[2] { 3, 5 };            //Object obj1 = asm.CreateInstance("ConsoleApplication2.Calculator", true, BindingFlags.Default, null, parameters, null, null);            //Calculator cal = (Calculator)obj1;            //Type t = typeof(Calculator);            //Calculator cal = new Calculator(3, 5);            //int result = (int)t.InvokeMember("Add", BindingFlags.InvokeMethod, null, cal, null);            //Console.WriteLine("result:" + result);            //Type t = typeof(Calculator);            //Object[] parameters = new Object[2] { 3, 5 };            //t.InvokeMember("Add", BindingFlags.InvokeMethod, null, t, parameters);            //Type t = typeof(Calculator);            //Calculator cal = new Calculator(3, 5);            //MethodInfo mi = t.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);            //mi.Invoke(cal, null);            //Type t = typeof(Calculator);            //Object[] parameters = new Object[2] { 6, 9 };            //MethodInfo mi = t.GetMethod("Add", BindingFlags.Public | BindingFlags.Static);            //mi.Invoke(null, parameters);            Console.ReadKey();        }    }    public class Message { }    public class TestClass    {        [Obsolete("请使用新方法")]        public static void ShowMsg()        {            Console.WriteLine("旧MSG");        }        public static void ShowMsg(Message msg)        {            Console.WriteLine("新MSG");        }    }    public class Calculator    {        private int x;        private int y;        public Calculator()        {            x = 0;            y = 0;            Console.WriteLine("Calculate()");        }        public Calculator(int x, int y)        {            this.x = x;            this.y = y;            Console.WriteLine("Calculate(int x, int y)");        }        public int Add()        {            int total = 0;            total = x + y;            Console.WriteLine("invoke instance method");            Console.WriteLine(string.Format("{0}+{1}={2}", x, y, total));            return total;        }        public static void Add(int x, int y)        {            int total = x + y;            Console.WriteLine("invoke static method");            Console.WriteLine(string.Format("{0}+{1}={2}", x, y, total));        }    }}
View Code

 

第15章 .NET中的反射