找传奇、传世资源到传世资源站!

C#反射调用

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{ class PrivateField { public delegate bool ReturnBoolHandler(string info); public delegate void TestHandler(string msg); public event ReturnBoolHandler ReturnBoolEvent; public event TestHandler TestEvent; } class Program { public static void s_TestEvent(string msg) { Console.WriteLine(msg); } static void Main(string[] args) { Assembly ass = Assembly.Load("ConsoleApplication1"); object structInstance = ass.CreateInstance("ConsoleApplication1.PrivateField"); Type structType = structInstance.GetType(); EventInfo eventInfo = structType.GetEvent("TestEvent", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); Type tDelegate = eventInfo.EventHandlerType; MethodInfo miHandler = typeof(Program).GetMethod("s_TestEvent", BindingFlags.Public | BindingFlags.Static); Delegate d = Delegate.CreateDelegate(tDelegate, miHandler); MethodInfo miAddHandler = eventInfo.GetAddMethod(); object[] addHandlerArgs = { d }; miAddHandler.Invoke(structInstance, addHandlerArgs); FieldInfo _Field = structType.GetField("TestEvent", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); if (_Field != null) { object _FieldValue = _Field.GetValue(structInstance); if (_FieldValue != null && _FieldValue is Delegate) { Delegate _ObjectDelegate = _FieldValue as Delegate; _ObjectDelegate.DynamicInvoke(new object[] { "Sandy" }); } } } }}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复