如何使用数字创建枚举? [英] How can I create an enum using numbers?

查看:19
本文介绍了如何使用数字创建枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C# 中仅使用数字来创建枚举?在我的程序中,我有一个变量 Gain,它只能设置为 1、2、4 和 8.我正在使用 propertygrid 控件来显示和设置这个值.如果我要创建这样的枚举...

Is it possible to make an enum using just numbers in C#? In my program I have a variable, Gain, that can only be set to 1, 2, 4, and 8. I am using a propertygrid control to display and set this value. If I were to create an enum like this...

 private enum GainValues {One, Two, Four, Eight}

我将增益变量设为 GainValues 类型,然后属性网格中的下拉列表将仅显示增益变量的可用值.问题是我希望增益值以数字方式读取而不是单词.但我无法创建这样的枚举:

and I made my gain variable of type GainValues then the drop-down list in the propertygrid would only show the available values for the gain variable. The problem is I want the gain values to read numerically an not as words. But I can not create an enum like this:

 private enum GainValues {1,2,4,8}

那么还有其他方法吗?也许创建一个自定义类型?

So is there another way of doing this? Perhaps creating a custom type?

推荐答案

这不是 enums 的工作方式. 枚举允许您命名特定值,以便您可以更明智地在代码中引用它.

This isn't how enums work. An enumeration allow you to name a specific value so that you can refer to it in your code more sensibly.

如果你想限制有效数字的域,枚举可能不是正确的选择.另一种方法是创建一个有效值的集合用作收益:

If you want to limit the domain of valid numeric, enums may not be the right choice. An alternative, is to just create a collection of valid values that can be used as gains:

private int[] ValidGainValues = new []{ 1, 2, 4, 8};

如果您想让它更安全,您甚至可以使用私有构造函数创建自定义类型,将所有有效值定义为静态的公共实例,然后以这种方式公开它们.但是您仍然必须为每个有效值指定一个名称 - 因为在 C# 中成员/变量名称不能以数字开头(尽管它们可以包含它们).

If you want to make this more typesafe, you could even create a custom type with a private constructor, define all of the valid values as static, public instances, and then expose them that way. But you're still going to have to give each valid value a name - since in C# member/variable names cannot begin with a number (although they can contain them).

现在,如果您真正想要的是为 GainValues 枚举中的条目分配特定值,您可以这样做:

private enum GainValues { One = 1, Two = 2, Four = 4, Eight = 8 };

这篇关于如何使用数字创建枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆