是否可以在没有自定义函数的情况下从该对象外部引发该对象的事件
public class a
{
public event eventhandler test;
public void RaiseTest(){//fire test}
}
是否可以从此类外部对此类进行测试,而不调用该方法?
基本上,我有大量必须根据外部源引发的事件,并且不想为每个事件创建 Raise() 函数。
是否可以创建一个通用 Raise() 来接受要引发的事件作为参数? 因此它仍然会从类内部调用?
public class a
{
public event eventhandler test;
public void RaiseTest(){//fire test}
}
Is it possible to raise test on this class, from outside this class, without calling the method?
Basically I have a large number of events which must be raised based on an external source, and do not want to create a Raise() function for each one.
Is it possible to create a generic Raise() that accepts the event to be raised as a parameter? therefore it would still be called from inside the class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过反射来做到这一点,但它不太明显。 如果在 C# 中声明事件,则会向类中添加一个字段,其中包含事件名称+“Event”。 如果您对该字段调用 GetValue,它将返回一个 MulticastDelegate 实例。
一旦你有了 MulticastDelegate,你就可以获取调用列表,并依次调用每个成员:
请注意,这需要从实例中获取 NonPublic 字段,因此它只能在完全信任的情况下工作,并且非常有限。
是的。 修改上面的代码来做到这一点是相当容易的。 只需用此替换“myClassInstance”即可。 这实际上也将允许它在完全信任的情况下正常工作,因为 NonPublic BindingFlag 将不再是问题。
You can do this via Reflection, but it is less than obvious. If you declare an event in C#, a field will be added to the class with the event name + "Event". If you call GetValue on the field, it will return a MulticastDelegate instance.
Once you have the MulticastDelegate, you can get the invocation list, and invoke each member in turn:
Note that this requires getting a NonPublic field from the instance, so it will only work in full trust, and is very limited.
Yes. It would be fairly easy to modify the above code to do this. Just replace "myClassInstance" with this. This will actually allow this to work properly in full trust, as well, since the NonPublic BindingFlag will no longer be an issue.
简短的回答:不。
只有声明该事件的类才能引发它
我不这么认为,至少不容易......即使使用反射,也没有
EventInfo.Invoke
方法。 AFAIK,引发事件的唯一方法是在类编辑中静态地进行:实际上它可以完成(参见里德的答案),但限制是应用程序必须在完全信任的情况下运行。
Short answer : no.
Only the class declaring the event can raise it
I don't think so, at least not easily... Even using reflection, there is no
EventInfo.Invoke
method. AFAIK, the only way to raise the event is statically from within the classEDIT: actually it can be done (see Reed's answer), but with the limitation that the app has to run in full trust.