Compile Time Conversion of uint to int in C#

2019-06-21 10:14发布

问题:

I've got an enum like this in an old piece of code:

[Flags]
public enum Example: uint
{    
    Foo = 0x00000001,
    Bar = 0xC0000000
}

Now, FxCop is complaining about this enum using uint rather than int as it's backing field. (And I've been tasked with getting this code as FxCop clean as possible...) But there is an existing enum value which uses the high order bit of the enum, and I can't change this because it has been persisted into an on-disk format. When I try to compile this, the C# compiler rightly complains:

error CS0266: Cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists (are you missing a cast?)

So, I was going to change it to this instead:

[Flags]
public enum Example
{    
    Foo = 0x00000001,
    Bar = (int)0xC0000000
}

However, I'm not positive that I can rely on this not throwing arithmetic exceptions, or not being handled correctly when being read or written to disk. Can I rely on the bit format here matching the format it used when the enum was backed by an unsigned int?

回答1:

Use the unchecked keyword here and you will be ok; the persisted bit pattern will be what you expect.

[Flags]
public enum Example
{
    Foo = 0x00000001,
    Bar = unchecked((int)0xC0000000);
} 


回答2:

Thomas's answer is 100% right, but I will add my three cents to it: instead of "fixing" your code which was already correct, you can always supress FxCop rules for some part of the code.

See How do I suppress FxCop rule 'DoNotCatchGeneralExceptionTypes' with SupressMessage? and it's accepted answer for example of use. Everything is set in the code and .csproj, so all such supression settings stay with the code when given away to the end client.



标签: c# clr