简体   繁体   English

如何在另一个枚举中设置枚举值?

[英]How do I set an enum value inside another enum?

I want something like this. 我想要这样的东西。

public enum AgeGroup  
{  
    Teenager = new enum { FromAge = 16, ToAge = 17 },  
    young = new enum { FromAge = 18, ToAge = 24  }   
}

By this I want access it like AgeGroup.Teenager.FromDate . 通过这个,我想像AgeGroup.Teenager.FromDate一样访问它。

A nested enum is not possible. 嵌套枚举是不可能的。

You can change your parent enum to a class, and it will work: 您可以将您的父枚举更改为一个类,它将起作用:

public class AgeGroup
{
    public enum Teegaer
    {
        FromAge = 16, ToAge = 17
    }

    public enum young
    {
        FromAge = 18, ToAge = 24
    }
}

An alternative approach is to create a static class : 另一种方法是创建一个静态类

public static class AgeGroup
{
   public static class TeenAge
   {
      public static readonly int FromAge = 16;
      public static readonly int ToAge = 17;
   }

  public static class YoungAge
   {
      public static readonly int FromAge = 18;
      public static readonly int ToAge = 21;
   }
}

Now you can refer to the variable, as below: 现在,您可以引用该变量,如下所示:

int teenAgeStarting = AgeGroup.TeenAge.FromAge  //16
int youngAgeStarting = AgeGroup.YoungAge.FromAge  //18

Implementation: DotNetFiddler 实施: DotNetFiddler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问此 class 中的枚举值? - How do I access an enum value in this class? 如何将枚举值设置为 GroupBox 内的单选按钮 - How to set enum value to Radio Buttons inside of GroupBox C# - 如何在具有属性的枚举中找到键值? - C# - how do I find a key value inside an enum with a property? 如何测试按位枚举是否包含来自C#中另一个按位枚举的任何值? - How do I test if a bitwise enum contains any values from another bitwise enum in C#? 如何更改枚举元素内的任何变量? - How do i change any variables inside of a enum element? 如何将绑定到枚举的ComboBox的初始SelectedItem设置为包含该枚举的对象的Value? - How can I set the initial SelectedItem for a ComboBox bound to an enum, to a Value of an object containing that enum? 如何将枚举类型的值传递给另一个枚举变量? - How to pass an value of type enum to another enum variable? 如何定义一个枚举有多个值是另一个枚举 - How to define an enum has multiple value that is another enum 如何通过解析具有相同命名常量的另一个枚举来获取枚举值 - How to get enum value by parsing another enum with same named constants 如何根据Enum的整数值设置哪个类型为Enum的propety - How to set propety which type is Enum based on the integer value of the Enum
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM