Why Enum's HasFlag method need boxing?

前端 未结 6 811
时光取名叫无心
时光取名叫无心 2020-12-10 03:45

I am reading \"C# via CLR\" and on page 380, there\'s a note saying the following:

Note The Enum class defines a HasFlag method defined as follows

6条回答
  •  春和景丽
    2020-12-10 04:13

    Moreover, there's more than single boxing in Enum.HasFlag:

    public bool HasFlag(Enum flag)
    {
        if (!base.GetType().IsEquivalentTo(flag.GetType()))
        {
            throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", new object[]
            {
                flag.GetType(),
                base.GetType()
            }));
        }
        ulong num = Enum.ToUInt64(flag.GetValue());
        ulong num2 = Enum.ToUInt64(this.GetValue());
        return (num2 & num) == num;
    }
    

    Look at GetValue method calls.

    Update. Looks like MS had optimized this method in .NET 4.5 (the source code has been downloaded from referencesource):

        [System.Security.SecuritySafeCritical]
        public Boolean HasFlag(Enum flag) { 
            if (flag == null)
                throw new ArgumentNullException("flag"); 
            Contract.EndContractBlock(); 
    
            if (!this.GetType().IsEquivalentTo(flag.GetType())) { 
                throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType()));
            }
    
            return InternalHasFlag(flag); 
        }
    
        [System.Security.SecurityCritical]  // auto-generated 
        [ResourceExposure(ResourceScope.None)]
        [MethodImplAttribute(MethodImplOptions.InternalCall)] 
        private extern bool InternalHasFlag(Enum flags);
    

提交回复
热议问题