我是否总是必须进行枚举或者我做错了什么?
如果我有一个非常简单的像这样的整数枚举。
enum alignment { left, center, right}
我希望数据类型是 int,我理解这是默认值,并且值是 left = 0,center = 1,right = 2。
但是如果我尝试使用枚举中的值,就像
header.Alignment = alignment.center;
我被告知的那样我需要将alignment.center 转换为int。这没什么大不了的,但我想知道我是否做错了什么,或者这就是枚举的工作方式。
if I have a very simple enum of ints like this.
enum alignment { left, center, right}
Where I want the datatype to be an int, which I understand is the default, and the values to be left = 0, center = 1, right = 2.
But if I try and use a value from the enum like
header.Alignment = alignment.center;
I am told that I need to cast alignment.center to an int. which is no big deal but I am wondering if I am doing something wrong or is that just the way enums work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
header.Alignment
的类型为int
,那么是的,您始终必须转换为int
。您可以将
header.Alignment
设为alignment
类型,然后就无需进行强制转换。但是,如果您正在处理仅接受int
的遗留代码或第三方代码,那么您就不走运了。if
header.Alignment
is of typeint
, then yes, you always have to cast to anint
.You could make
header.Alignment
of typealignment
, and then you'd never have to cast. If you're dealing with legacy or third-party code that only accepts anint
, however, you're out of luck.如果
header.Alignment
属性是一个整数,则需要对其进行强制转换。也就是说,将 Alignment 属性更改为实际上的 Alignment 类型可能更有意义。这样,您在设置它时就不需要进行强制转换,并且如果您需要它,您仍然可以访问整数值。
If the
header.Alignment
property is an integer you will need to cast it.That said it would probably make more sense to change the Alignment property to actually be of type Alignment. Then you would not need to cast when you are setting it and you would still have access to the integer value if you ever needed it.
枚举后备存储是一个 int,但您不能轻松地将其用作 int。枚举的思想是拥有一个强类型常量集合,以便您可以将它们用作对齐值。当你将它用作 int 时,你就把强类型扔出了窗口。您应该将标头的 Alignment 属性更改为 Alignment 类型而不是 int 类型。
The enum backing store is an int, but you can't use it as an int easily. the idea of an enumeration is to have a strongly typed collection of constants so you can use them as, say, an alignment value. when you us it as an int, you throw that strong typing out the window. You should change the Alignment property of your header to be of type Alignment rather than an int.
是的。从枚举类型(对齐)转换为整型需要显式转换。
Yes. An explicit cast is needed to convert from enum type (alignment) to an integral type.