在 IL 中可以对空引用调用实例方法是否正确?
有没有例子可以证明这一点..?
是的,这是可能的,只要该方法不使用this
因为 CLR 不会对以下内容进行空检查call
指示。
You would have to modify the IL by hand as the C# compiler would almost always generate a callvirt
instruction1.
有关详细信息和示例,请参阅此博客文章:
在空引用上调用实例方法 https://web.archive.org/web/20100724141113/http://www.pvle.be:80/2010/07/instance-methods-called-on-null-references/
Sample
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 18 (0x12)
.maxstack 1
.locals init ([0] class SomeClass o, [1] string hello)
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call instance string SomeClass::GetHello()
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: call void [mscorlib]System.Console::WriteLine(string)
IL_0010: nop
IL_0011: ret
}
1In fact the reason that the C# compiler emits callvirt
even in cases where a simple call
instruction would be sufficient is to prevent calling instance methods on null references. With this behavior of the compiler users will get a NullReferenceException
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? https://web.archive.org/web/20160112223951/http://blogs.msdn.com/b/ericgu/archive/2008/07/02/why-does-c-always-use-callvirt.aspx Gishu https://stackoverflow.com/users/1695/gishu also has a nice explanation in a related question https://stackoverflow.com/questions/845657/why-is-the-c-sharp-compiler-emitting-a-callvirt-instruction-for-a-gettype-meth/845721#845721.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)