Byu*_*eng 4 c# reflection events delegates invoke
我有2个DLL,A.dll包含:
namespace Alphabet
{
public delegate void TestHandler();
public class A
{
private void DoTest()
{
Type type = Assembly.LoadFile("B.dll").GetType("Alphabet.B");
Object o = Activator.CreateInstance(type);
string ret = type.InvokeMember("Hello", BindingFlags.InvokeMethod | BindingFlags.Default, null, o, null);
}
}
}
Run Code Online (Sandbox Code Playgroud)
和B.dll包含
namespace Alphabet
{
public class B
{
public event TestHandler Test();
public string Hello()
{
if (null != Test) Test();
return "Hello";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用InvokeMember从B.dll获取结果,我也想Test()在返回结果之前使用B.dll .那么,我如何通过反射delegate将其连接event到B.dll?
任何帮助将不胜感激!
获取活动,typeof(B).GetEvent("Test")然后将其连接起来EventInfo.AddEventHandler.示例代码:
using System;
using System.Reflection;
public delegate void TestHandler();
public class A
{
static void Main()
{
// This test does everything in the same assembly just
// for simplicity
Type type = typeof(B);
Object o = Activator.CreateInstance(type);
TestHandler handler = Foo;
type.GetEvent("Test").AddEventHandler(o, handler);
type.InvokeMember("Hello",
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.InvokeMethod,
null, o, null);
}
private static void Foo()
{
Console.WriteLine("In Foo!");
}
}
public class B
{
public event TestHandler Test;
public string Hello()
{
TestHandler handler = Test;
if (handler != null)
{
handler();
}
return "Hello";
}
}
Run Code Online (Sandbox Code Playgroud)