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

前端 未结 6 937
孤城傲影
孤城傲影 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:45

    Other than a few nops, reflector indictes the only differences are in the IsGuid method:

    DEBUG:

    .method public hidebysig static bool IsGuid(object item) cil managed
    {
        .maxstack 2
        .locals init (
            [0] bool CS$1$0000)
        L_0000: nop 
        L_0001: ldarg.0 
        L_0002: isinst [mscorlib]System.Guid
        L_0007: ldnull 
        L_0008: cgt.un 
        L_000a: stloc.0 
        L_000b: br.s L_000d
        L_000d: ldloc.0 
        L_000e: ret 
    }
    

    RELEASE:

    .method public hidebysig static bool IsGuid(object item) cil managed
    {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: isinst [mscorlib]System.Guid
        L_0006: ldnull 
        L_0007: cgt.un 
        L_0009: ret 
    }
    

    I'm not fluent enough to explain these differences but this is a community wiki answer so maybe somebody else can enlighten us?

    Changing the method to make it generic works around this (possible bug?)

    public static bool IsGuid(T item)
    {
        return item is Guid;
    }
    

    As does forcing it into a local varible (but it must be used in the method to prevent the optimizations kicking in):

    public static bool IsGuid(object item)
    {
        bool a = item is Guid;
        a.ToString();
        return a;
    }
    

提交回复
热议问题