如何使用数字创建枚举?

发布于 2024-09-03 09:44:37 字数 381 浏览 7 评论 0原文

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

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

并且我将增益变量设置为 GainValues 类型,那么属性网格中的下拉列表将仅显示增益变量的可用值。问题是我希望增益值以数字形式读取,而不是以文字形式读取。但我无法创建这样的枚举:

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

那么还有另一种方法可以做到这一点吗?也许创建一个自定义类型?

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}

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(7

只有一腔孤勇 2024-09-10 09:44:37

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

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

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

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

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

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

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

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).

Now if what you really want, is to assign specific values to entries in a GainValues enumeration, that you CAN do:

private enum GainValues { One = 1, Two = 2, Four = 4, Eight = 8 };
日久见人心 2024-09-10 09:44:37

已经有很多关于这个问题的答案,但我将提供另一个解决方案。如果您希望控件显示实际数字,而不是控件中数字的英文单词,则可以使用数据注释。

using System.ComponentModel.DataAnnotations;

private enum GainValues 
{
 [Display(Name = "1")]
 One,
 [Display(Name = "2")]
 Two,
 [Display(Name = "4")] 
 Four, 
 [Display(Name = "8")]
 Eight
}

这在您的程序中想要使用友好名称而不是成员的实际名称的任何地方都很有用。

There have been a good amount of answers on this already however I will offer another solution. If you want your control to show an actual number as opposed to the english word for the number in your control you can use data annotations.

using System.ComponentModel.DataAnnotations;

private enum GainValues 
{
 [Display(Name = "1")]
 One,
 [Display(Name = "2")]
 Two,
 [Display(Name = "4")] 
 Four, 
 [Display(Name = "8")]
 Eight
}

This is useful anywhere in your program where you want to use a friendly name as opposed to a member's actual name.

捎一片雪花 2024-09-10 09:44:37

如果我正确理解了原来的问题,答案可能是这样的:

您可以通过简单地使用下划线前缀来获取检查器中枚举中列出的数字,例如:

public enum MyNumbers{ _1, _2, _3, _4 };
public MyNumbers myNumbers;

希望这有帮助!

If I understood the original question correctly, the answer may be this:

You can get numbers listed in an enum in the inspector by simply using an underscore prefix, e.g:

public enum MyNumbers{ _1, _2, _3, _4 };
public MyNumbers myNumbers;

Hope this is helps!

橙味迷妹 2024-09-10 09:44:37
private enum GainValues { One = 1, Two = 2, Four = 4, Eight = 8 }

应该有效。

更新:好吧,我想我误解了你的意思。

也许您可以使用 KeyValuePair ,然后将名称和值分别绑定到 Key 和 Value 属性。

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

should work.

Update: OK, I think I misunderstood you there.

Maybe you could use a KeyValuePair<string, int> and then bind the name and the value to the Key and Value property respectively.

青巷忧颜 2024-09-10 09:44:37

不幸的是,C# 中的符号可以包含数字,但不能以数字开头。所以你必须使用言语。

或者,您可以执行 Gain1、Gain2 等。

或者您可以完全放弃枚举并使用常量和内部处理。

Unfortunately, symbols in C# can contain numbers, but cannot start with numbers. So you're gonna have to use words.

Alternatively, you could do Gain1, Gain2, etc.

Or you could forgo an enum altogether and use constants and internal processing.

只是一片海 2024-09-10 09:44:37

在枚举中使用显式赋值:

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

然后要枚举这些值,请执行以下操作:

GainValues currentVal;

foreach(currentVal in Enum.GetValues(typeof(GainValues))
{
   // add to combo box (or whatever) here
}

然后您可以根据需要转换为整数或从整数转换:

int valueFromDB = 4;

GainValues enumVal = (GainValues) valueFromDB;

// enumVal should be 'Four' now

use explicit value assignment in the enum:

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

Then to enumerate through these values do as follows:

GainValues currentVal;

foreach(currentVal in Enum.GetValues(typeof(GainValues))
{
   // add to combo box (or whatever) here
}

Then you can cast to/from ints as necessary:

int valueFromDB = 4;

GainValues enumVal = (GainValues) valueFromDB;

// enumVal should be 'Four' now
苏佲洛 2024-09-10 09:44:37

您可以使用一个自定义列表作为下拉列表的数据源。

代码隐藏:

using GainItem = KeyValuePair<string, int>;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<GainItem> dic = new List<GainItem>();
            dic.Add(new GainItem("First", 1));
            dic.Add(new GainItem("Second", 2));
            dic.Add(new GainItem("Fourth", 4));
            ddl.DataSource = dic;
            ddl.DataBind();
        }


    }

    protected void btn_Click(object sender, EventArgs e)
    {
        Response.Write(ddl.SelectedValue);
    }
}

Asp 页面:

    <div>
    <asp:DropDownList runat="server" ID="ddl" DataValueField="Value" DataTextField="Key" />
    <asp:Button ID="btn" runat="server" OnClick="btn_Click" />
   </div>

此外,您可以使用枚举来设置默认值,...

希望这有帮助

You can use one custom list as a datasource for your drop down list.

Code Behind:

using GainItem = KeyValuePair<string, int>;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<GainItem> dic = new List<GainItem>();
            dic.Add(new GainItem("First", 1));
            dic.Add(new GainItem("Second", 2));
            dic.Add(new GainItem("Fourth", 4));
            ddl.DataSource = dic;
            ddl.DataBind();
        }


    }

    protected void btn_Click(object sender, EventArgs e)
    {
        Response.Write(ddl.SelectedValue);
    }
}

Asp Page:

    <div>
    <asp:DropDownList runat="server" ID="ddl" DataValueField="Value" DataTextField="Key" />
    <asp:Button ID="btn" runat="server" OnClick="btn_Click" />
   </div>

In addition, you can have enum for setting default value, ...

hope this helps

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