首页 > 代码库 > 第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)); } }}
第15章 .NET中的反射
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。