在C#中将uint编译时转换为int

在C#中将uint编译时转换为int

本文介绍了在C#中将uint编译时转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在旧代码中有一个这样的枚举:

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

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

现在,有关此枚举的用法uint而不是int作为后备字段。 (而且我的任务是尽可能地将代码作为FxCop清理干净……)但是有一个现有的枚举值使用枚举的高阶位,我无法更改它,因为它已被持久化为磁盘格式。当我尝试编译它时,C#编译器正确地抱怨:

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
}

但是,我不是可以肯定的是,我可以依靠它不会引发算术异常,或者在读取或写入磁盘时无法正确处理它。我可以依靠这里的位格式来匹配由无符号int支持的枚举时使用的位格式吗?

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?

推荐答案

使用此处未选中的关键字,您就可以了;

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);
}

这篇关于在C#中将uint编译时转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:40