在 IL 中对空引用调用实例方法
在 IL 中可以对空引用调用实例方法是否正确? 有没有例子可以证明这一点..?
Is it correct that a instance method can be called on a null reference in IL..?
Is there any example to show this..?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是可能的,只要该方法不使用
this
即可,因为 CLR 不会对call
指令进行 null 检查。您必须手动修改 IL,因为 C# 编译器几乎总是生成
callvirt
指令1。有关详细信息和示例,请参阅此博客文章:
示例
1实际上是 C# 编译器发出
的原因callvirt
即使在简单的call
指令就足以防止在空引用上调用实例方法的情况下。通过编译器的这种行为,用户将得到 NullReferenceException ,因此可以避免在空指针上调用方法的奇怪情况。 Eric Gunnerson 在不久前的一篇博客文章中解释了这一点:为什么 C# 总是使用 callvirt? < a href="https://stackoverflow.com/users/1695/gishu">Gishu 在 相关问题。Yes, this is possible, as long as the method doesn't use
this
because the CLR does not do a null check forcall
instructions.You would have to modify the IL by hand as the C# compiler would almost always generate a
callvirt
instruction1.See this blog post for details and an example:
Sample
1In fact the reason that the C# compiler emits
callvirt
even in cases where a simplecall
instruction would be sufficient is to prevent calling instance methods on null references. With this behavior of the compiler users will get aNullReferenceException
so the weird situation of calling a method on a null pointer is avoided. Eric Gunnerson explained this in a blog post some time ago: Why does C# always use callvirt? Gishu also has a nice explanation in a related question.请参阅我的 博客条目以获取信息。
IL 代码示例:
See my blog entry for info.
IL code sample:
CLR 不需要它,它是语言的实现细节。 C# 和 VB.NET 执行测试。 C++/CLI 是一种著名的托管语言,它允许这样做。只要实例方法不引用任何类成员,就不会出错。如果是这样,NullReferenceException 将像平常一样引发,只是让您很难找出原因。
The CLR doesn't require it, it is an implementation detail of the language. C# and VB.NET perform the test. C++/CLI is a notable managed language that permits it. As long as the instance method doesn't reference any class members then nothing goes wrong. If is does, NullReferenceException will be raised as normal, merely giving you a hard time finding out why.