如何在 C# 中将枚举类型定义为 float 或 double
此处表示枚举的可能类型 是
byte
、sbyte
、short
、ushort
、int
、uint
, long
或 ulong
。
如果我需要 float
或 double
来定义百分比增量(例如 1.5
或 2.5
)怎么办?我被困住了吗?
正如这里所说: http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80 %94Enum_Design
枚举是具有一组静态常量的结构。原因是 遵循这个指南是因为你会得到一些额外的编译器 和反射支持(如果您定义枚举而不是手动定义) 具有静态常量的结构。
既然枚举是一组常量,为什么我不能有浮点常量?
更新:这里说的是: http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80 %94Enum_Design “您是否知道 CLR 支持具有 float 或 double 基础类型的枚举,尽管大多数语言不选择公开它?”
由于我只使用 c#,有没有办法通过一些技巧来做到这一点?
It says here that the possible types for an enum
are byte
, sbyte
, short
, ushort
, int
, uint
, long
, or ulong
.
What if I need a float
or a double
to define percentage increments such as 1.5
or 2.5
for example? Am I stuck?
As said here:
http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design
An enum is a structure with a set of static constants. The reason to
follow this guideline is because you will get some additional compiler
and reflection support if you define an enum versus manually defining
a structure with static constants.
Since an enum is a set of constants, why can't I have float constants ?
Update: it is said here:
http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design
"Did you know that the CLR supports enums with an underlying type of float or double even though most languages don't choose to expose it?"
Since I'm only using c# is there a way to do so with some hacks ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管 CLR 本身支持浮点枚举,但 C# 设计者选择不在语言中公开这一点(请参阅 http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design)。您可以像 John Saunders 的答案中那样使用常量,也可以定义一个具有相乘值的整数枚举,然后在需要该值时将它们除回去。
不过,用例肯定会很有趣。你为什么需要/想要这个?
Although the CLR itself supports floating point enums, C# designers chose not to expose this in the language (see http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Enum_Design). You can either use constants as in John Saunders' answer, or you can define an integer enum with multiplied values and then divide them back if/when you need the value.
The use case would be definitely interesting, though. Why do you need/want this?
是的,你被困在那里了。您不能将
enum
与浮点类型一起使用。但是,您可以将静态类
与常量一起使用:并且它在 IntelliSense 中看起来有些接近。或者,您可能只想使用常量:
Yes, you're stuck there. You can't use
enum
s with floating-point types. You can use astatic class
with constants, however:And it will look somewhat close in IntelliSense. Alternatively, you may just want to use constants:
您将必须使用一组常量:
You will have to use a set of constants: