当我用的是运营商,为什么只有一个空支票IL代码? [英] When I use is operator why there is only a null-check in IL code?

查看:153
本文介绍了当我用的是运营商,为什么只有一个空支票IL代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是如何是运营商 C#实施。而我写了一个简单的测试程序(没有特别的,只是为了演示):

I was wondering how is is operator implemented in C#.And I have written a simple test program (nothing special, just for demonstration purposes):

class Base
{
    public void Display() {  Console.WriteLine("Base"); }
}

class Derived : Base { }

class Program
{
    static void Main(string[] args)
    {
        var d = new Derived();

        if (d is Base)
        {
            var b = (Base) d;
            d.Display();
        }
    }
}

和看着生成的 IL 代码:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       27 (0x1b)
  .maxstack  2
  .locals init ([0] class ConsoleApplication1.Derived d,
           [1] bool V_1,
           [2] class ConsoleApplication1.Base b)
  IL_0000:  nop
  IL_0001:  newobj     instance void ConsoleApplication1.Derived::.ctor()
  IL_0006:  stloc.0  // set derived (d)
  IL_0007:  ldloc.0 // load derived
  IL_0008:  ldnull // push a null reference
  IL_0009:  ceq   // and compare with d !?
  IL_000b:  stloc.1
  IL_000c:  ldloc.1
  IL_000d:  brtrue.s   IL_001a
  IL_000f:  nop
  IL_0010:  ldloc.0
  IL_0011:  stloc.2
  IL_0012:  ldloc.0
  IL_0013:  callvirt   instance void ConsoleApplication1.Base::Display()
  IL_0018:  nop
  IL_0019:  nop
  IL_001a:  ret
} // end of method Program::Main

当我看<一结束HREF =http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldnull%28v=vs.110%29.aspx>文档它说:

推空引用(O型)到计算堆栈。

Pushes a null reference (type O) onto the evaluation stack.

ldnull 。 Ofcourse,我没想到在这里看到一个源代码,但我很惊讶,只存在一个空check.I认为这可能与有关编译器优化,因为派生基础派生所以没有检查有关types.then兼容性我检查出来,看到优化是关闭的。当我打开优化甚至没有的空检查

for ldnull. Ofcourse, I wasn't expecting to see a source code here, but I'm surprised that there is only a null-check.I thought it may be relevant with compiler optimizations because Derived derives from Base so there is no check the compatibility about the types.then I check out and see that the optimizations are turned off.when I turn on the optimizations there wasn't even null-check.

所以,问题是为什么会出现约产生什么运营商?为什么我看到的只是一个空检查?是它在某种程度上与相关是运营商,我不能看?

So the question is why there is nothing generated about is operator ? why I see only a null-check ? Is it somehow relevant with is operator and I couldn't see ?

推荐答案

类型 D 导出,它的类型总是基本无效即可。这就是为什么非优化的代码只为null检查。

The type of d is Derived, which is always of type Base or null. That's why the non-optimized code only checks for null.

优化的代码,因为优化器知道 D没有做的检查都不为空(因为你分配一个新对象的话)和分配后并没有改变。

The optimized code doesn't do a check at all because the optimizer knows that d is not null (since you assigned a new object to it) and didn't change after the assignment.

这篇关于当我用的是运营商,为什么只有一个空支票IL代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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