EventInfo.GetRaiseMethod()总是空 [英] EventInfo.GetRaiseMethod() always null

查看:102
本文介绍了EventInfo.GetRaiseMethod()总是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

event EventHandler MyEvent;

MyEvent += new EventHandler(someHandler);

if(this.GetEvent("MyEvent").GetRaiseMethod() == null)
{
  // Always true...
}

但是,为什么?当我添加一个处理程序,不应该 GetRaiseMethod()设置为 someHandler MethodInfo的

推荐答案

这是C#的一个怪癖,它不支持加薪访问。只有添加和删除。其他.NET语言,如VB.NET,F#和C ++ / CLI都支持他们,这是很好的CLI规范中的一个定义,命名为火。

This is a quirk of C#, it doesn't support raise accessors. Only add and remove. Other .NET languages like VB.NET, F# and C++/CLI do support them and it is well defined in the CLI spec, named "fire" in that one.

这是很难解释为什么C#团队跳过了,我从来没有见过一个很好的解释了。纯属猜测:这可能有一些与他们的愿望,以限制引发事件只对声明它的类的能力。同样的限制并不在C ++ / CLI存在。没有一个很好的解释然而,VB.NET也制约着它,但仍然有加薪的访问。这是一个有点损失,数十万小时必须已经失去了C#程序员在编写标准的提高事件模式以及诊断NRE费用时,他们忘了检查空。

It is hard to explain why the C# team skipped it, I've never seen a good explanation for it. Pure speculation: it may have had something to do with their desire to restrict the ability to raise events only to the class that declared it. This same restriction does not exist in C++/CLI. Not a great explanation however, VB.NET also restricts it but still has a raise accessor. It is a bit of a loss, hundreds of thousands of hours must have been lost by C# programmers writing the standard raise event pattern as well as diagnosing NREs when they forgot to check for null.

安美居,你永远不会得到任何东西,但空从GetRaiseMethod(),如果你反映code C#编写的。你不过总是得到一个非空的,当它被写在VB.NET,F#和C ++ / CLI。你必须挖掘出的后盾委托变量,如果你需要提高的情况下与反思,也可以是痛苦的。如果自动生成的添加/删除访问者被使用,则后盾变量具有相同的名称时,你可以用Type.GetField()检索,使用BindingFlags.NonPublic可| BindingFlags.Instance。

Anyhoo, you'll never get anything but null from GetRaiseMethod() if you reflect code written in C#. You'll however always get a non-null when it was written in VB.NET, F# or C++/CLI. You'll have to dig out the backing delegate variable if you need to raise the event with reflection, that can be painful. If the auto-generated add/remove accessors were used then the backing variable has the same name as the event and you can retrieve it with Type.GetField(), using BindingFlags.NonPublic | BindingFlags.Instance.

这篇关于EventInfo.GetRaiseMethod()总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆