C# 'is' type check on struct - odd .NET 4.0 x86 optimization behavior

前端 未结 6 940
孤城傲影
孤城傲影 2021-02-02 07:20

Update: I have filed a bug report with Microsoft Connect, please vote for it!

Update 2: Microsoft have marked the bug report as fixed

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 07:35

    Interestingly enough this works correctly:

    using System;
    public class Program
    {
        public static bool IsGuid(object item)
        {
            return item is Guid;
        }
    
        public static void Main()
        {
            Guid s = Guid.NewGuid();
            Console.Write(IsGuid(s));
        }
    }
    

    Here is the difference in the il:

    .method public hidebysig static void  Main() cil managed
    {
      .entrypoint
      // Code size       23 (0x17)
      .maxstack  1
      .locals init (valuetype [mscorlib]System.Guid V_0)
      IL_0000:  call       valuetype [mscorlib]System.Guid [mscorlib]System.Guid::NewGuid()
      IL_0005:  stloc.0
      IL_0006:  ldloc.0
      IL_0007:  box        [mscorlib]System.Guid
      IL_000c:  call       bool Program::IsGuid(object)
      IL_0011:  call       void [mscorlib]System.Console::Write(bool)
      IL_0016:  ret
    } // end of method Program::Main
    

提交回复
热议问题