从程序集订阅方法到我的应用程序中的事件
Subscribe method from assembly to an event in my application
假设我有一个事件,声明如下:
public class OnGooseHonkEvent{
public delegate void OnGooseHonk();
public static event OnGooseHonk OnGooseHonkEvent;
}
然后在编译为dll的程序集中,我有以下代码:
namespace ExampleMod
{
public class Class1
{
public Class1()
{
}
public void OnGooseHonk()
{
UntitledGooseAPI.Log("Goose Honked");
}
}
}
我怎样才能将 ExampleMod.Class1.OnGooseHonk
订阅到 OnGooseHonkEvent.OnGooseHonkEvent
?它必须通过 Assembly 模块来完成,因为我正在以编程方式从目录加载所有程序集。
我可能对 OnGooseHonkEvent
class 的设置方式有点困惑。将委托更改为可以在对象上调用的方法,并将 OnGooseHonkedEvent 设置为 Eventhandler<EventArgs>
而不是 event
,我得到了这个:
public class OnGooseHonkEvent
{
// Calling this will notify every event subscriber the goose has honked
public void HonkTheGoose()
{
OnGooseHonkedEvent?.Invoke(this, EventArgs.Empty);
}
public static event EventHandler<EventArgs> OnGooseHonkedEvent;
}
public class Class1
{
public Class1()
{
OnGooseHonkEvent.OnGooseHonkedEvent += OnGooseHonk;
}
public void OnGooseHonk(object sender, EventArgs e)
{
UntitledGooseAPI.Log("When any instance of OnGooseHonkEvent calls the HonkTheGoose() method, this should get fired");
}
}
假设我有一个事件,声明如下:
public class OnGooseHonkEvent{
public delegate void OnGooseHonk();
public static event OnGooseHonk OnGooseHonkEvent;
}
然后在编译为dll的程序集中,我有以下代码:
namespace ExampleMod
{
public class Class1
{
public Class1()
{
}
public void OnGooseHonk()
{
UntitledGooseAPI.Log("Goose Honked");
}
}
}
我怎样才能将 ExampleMod.Class1.OnGooseHonk
订阅到 OnGooseHonkEvent.OnGooseHonkEvent
?它必须通过 Assembly 模块来完成,因为我正在以编程方式从目录加载所有程序集。
我可能对 OnGooseHonkEvent
class 的设置方式有点困惑。将委托更改为可以在对象上调用的方法,并将 OnGooseHonkedEvent 设置为 Eventhandler<EventArgs>
而不是 event
,我得到了这个:
public class OnGooseHonkEvent
{
// Calling this will notify every event subscriber the goose has honked
public void HonkTheGoose()
{
OnGooseHonkedEvent?.Invoke(this, EventArgs.Empty);
}
public static event EventHandler<EventArgs> OnGooseHonkedEvent;
}
public class Class1
{
public Class1()
{
OnGooseHonkEvent.OnGooseHonkedEvent += OnGooseHonk;
}
public void OnGooseHonk(object sender, EventArgs e)
{
UntitledGooseAPI.Log("When any instance of OnGooseHonkEvent calls the HonkTheGoose() method, this should get fired");
}
}