我是否总是必须进行枚举或者我做错了什么?

发布于 2024-09-12 01:19:21 字数 328 浏览 2 评论 0原文

如果我有一个非常简单的像这样的整数枚举。

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

若水般的淡然安静女子 2024-09-19 01:19:21

如果 header.Alignment 的类型为 int,那么是的,您始终必须转换为 int

您可以将 header.Alignment 设为 alignment 类型,然后就无需进行强制转换。但是,如果您正在处理仅接受 int 的遗留代码或第三方代码,那么您就不走运了。

if header.Alignment is of type int, then yes, you always have to cast to an int.

You could make header.Alignment of type alignment, and then you'd never have to cast. If you're dealing with legacy or third-party code that only accepts an int, however, you're out of luck.

苄①跕圉湢 2024-09-19 01:19:21

如果 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.

攒眉千度 2024-09-19 01:19:21

枚举后备存储是一个 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.

╭ゆ眷念 2024-09-19 01:19:21

是的。从枚举类型(对齐)转换为整型需要显式转换。

Yes. An explicit cast is needed to convert from enum type (alignment) to an integral type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文