【问题标题】:How to set space on Enum如何在枚举上设置空间
【发布时间】:2010-11-09 06:25:55
【问题描述】:

我想在我的枚举上设置空间。这是我的代码示例:

public enum category
{
    goodBoy=1,
    BadBoy
}

我要设置

public enum category
{
    Good Boy=1,
    Bad Boy  
}

当我检索时,我想查看枚举的 Good Boy 结果

【问题讨论】:

  • 您的要求并不完全清楚。你能改写一下吗?
  • 在我的枚举“Good_Boy”集上,但在我的控制下,我想用 Space 替换 _ 怎么办
  • 您想在哪个控件上设置它?这很重要。

标签: c#


【解决方案1】:

这是不可能的,枚举器的名称中不能包含空格。

【讨论】:

    【解决方案2】:

    认为这可能已经涵盖,一些建议:

    只是无法击败 stackoverflow ;) 现在在这里太多了。

    【讨论】:

      【解决方案3】:

      您误解了枚举的用途。枚举用于编程目的,本质上是为数字命名。这是为了程序员在阅读源代码时的利益。

      status = StatusLevel.CRITICAL; // this is a lot easier to read...
      status = 5;                    // ...than this
      

      枚举不是用于显示目的,不应向最终用户显示。与任何其他变量一样,枚举不能在名称中使用空格。

      要将内部值与可以显示给用户的“漂亮”标签相关联,可以使用字典或哈希。

      myDict["Bad Boy"] = "joe blow";
      

      【讨论】:

      • 在我的枚举“Good_Boy”集上,但在我的控制下,我想用 Space 替换 _ 怎么办
      • 不要在用户可以看到的地方使用枚举名称。正如我之前所说,使用字典。这就是他们的目的。枚举用于编程级别的统一,而不是用于用户显示!
      • 问题是组合框的数据源通常没有在数据库中定义,而是它的源是一个枚举。我不确定这是一件坏事。
      【解决方案4】:

      .Net 中不能有带空格的枚举。当然,早期版本的 VB 和 C++ 可以做到这一点,但现在不行了。我记得在 VB6 中我曾经将它们括在方括号中,但在 C# 中没有。

      【讨论】:

        【解决方案5】:

        你为什么不使用 ToString() ?

        我的意思是当使用 ToString() 时,它会给出枚举值。只是你必须添加一些标识符来捕捉空间。例如:

        public enum category
        {
           good_Boy=1,
           Bad_Boy
        }
        

        当您在类别 a = ... 等代码中获得枚举时,您可以使用 ToString() 方法。它为您提供字符串的值。之后,您可以简单地将_更改为空字符串。

        【讨论】:

        • 这与价值观无关。他想写成 int x=(int)category.good Boy
        • 一个不错的解决方法。我在下面将您开发成一个完整的示例。
        【解决方案6】:

        你可以用DataAnnotations 来装饰你的枚举值,所以以下是正确的:

        using System.ComponentModel.DataAnnotations;
        
        public enum Boys
        {
            [Display(Name="Good Boy")]
            GoodBoy,
            [Display(Name="Bad Boy")]
            BadBoy
        }
        

        我不确定您为控件使用的 UI 框架,但当您在 ​​Razor 视图中键入 HTML.LabelFor 时,ASP.NET MVC 可以读取 DataAnnotations

        这里有一个扩展方法

        如果您不使用 Razor 视图,或者如果您想在代码中获取名称:

        public class EnumExtention
        {
            public Dictionary<int, string> ToDictionary(Enum myEnum)
            {
                var myEnumType = myEnum.GetType();
                var names = myEnumType.GetFields()
                    .Where(m => m.GetCustomAttribute<DisplayAttribute>() != null)
                    .Select(e => e.GetCustomAttribute<DisplayAttribute>().Name);
                var values = Enum.GetValues(myEnumType).Cast<int>();
                return names.Zip(values, (n, v) => new KeyValuePair<int, string>(v, n))
                    .ToDictionary(kv => kv.Key, kv => kv.Value);
            }
        }
        

        然后使用它:

        Boys.GoodBoy.ToDictionary()
        

        【讨论】:

        • 描述所需的命名空间是 System.ComponentModel
        • 耶; using System.ComponentModel.DataAnnotations;
        • 我认为这个命名空间只在 Web 应用程序中可用,而发帖人没有提到他正在使用的任何地方。
        • 我正在使用WinForms 类库项目的命名空间 - 我不认为它只是 ASP
        【解决方案7】:

        由于最初的问题是要求在枚举值/名称中添加一个空格,我想说下划线字符应该替换为空格,而不是空字符串。但是,最好的解决方案是使用注释。

        【讨论】:

          【解决方案8】:

          枚举器的名称中不能包含空格。

          我们知道 enum 是用于声明枚举的关键字。

          你可以检查扔这个链接 https://msdn.microsoft.com/en-us/library/sbbt4032.aspx

          【讨论】:

            【解决方案9】:

            在上面提到的 user14570 的(不错的)解决方法上进行开发,这是一个完整的示例:

                public enum MyEnum
                {
                    My_Word,
                    Another_One_With_More_Words,
                    One_More,
                    We_Are_Done_At_Last
                }
            
                internal class Program
                {
                    private static void Main(string[] args)
                    {
                        IEnumerable<MyEnum> values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
                        List<string> valuesWithSpaces = new List<string>(values.Select(v => v.ToString().Replace("_", " ")));
            
                        foreach (MyEnum enumElement in values)
                            Console.WriteLine($"Name: {enumElement}, Value: {(int)enumElement}");
            
                        Console.WriteLine();
                        foreach (string stringRepresentation in valuesWithSpaces)
                            Console.WriteLine(stringRepresentation);
                    }
                }
            

            输出:

            【讨论】:

              【解决方案10】:
              using System.ComponentModel;
              

              那么……

              public enum category
              {
                  [Description("Good Boy")]
                  goodboy,
                  [Description("Bad Boy")]
                  badboy
              }
              

              解决了!!

              【讨论】:

              • 请不要只是代码转储。提供有关它的解释,例如您可以使用属性...例如...因为...示例
              • 赞成这个答案,因为我在 Unity 环境中工作,并且 DataAnnotations 不可用。
              【解决方案11】:

              C# 现在有一个内置函数可以从枚举中获取描述。这是它的工作原理

              我的枚举:

              using System.ComponentModel.DataAnnotations;
              
              public enum Boys
              {
              [Description("Good Boy")]
              GoodBoy = 1,
              [Description("Bad Boy")]
              BadBoy = 2
              }
              

              这是在代码中检索描述的方法

              var enumValue = Boys.GoodBoy;
              string stringValue = enumValue.ToDescription();
              

              结果是:好孩子。

              【讨论】:

              • 你使用的是参考 System.ComponentModel.DataAnnotations;
              • 这对我不起作用。 Intellisense 无法识别 ToDescription()。我尝试使用 System.ComponentModel.DataAnnotations。您使用的是什么版本的 C#?什么图书馆?
              • 这肯定比我的解决方案更优雅,唯一的缺点是必须维护 2 个值列表,一个用于枚举,一个用于描述......
              • @jshockwave,你可以为此做一个扩展方法。我已经发布了一个例子。希望对您有所帮助。
              • .ToDescription() 似乎不存在。也许这是指this answer的代码?
              【解决方案12】:
              public enum MyEnum { With_Space, With_Two_Spaces } //I store spaces as underscore. Actual values are 'With Space' and 'With Two Spaces'
              
              public MyEnum[] arrayEnum = (MyEnum[])Enum.GetValues(typeof(MyEnum));
              
              string firstEnumValue = String.Concat(arrayEnum[0].ToString().Replace('_', ' ')) //I get 'With Space' as first value
              string SecondEnumValue = String.Concat(arrayEnum[1].ToString().Replace('_', ' ')) //I get 'With Two Spaces' as second value
              

              【讨论】:

                【解决方案13】:

                我使用正则表达式将值按大写字母拆分,然后立即加入一个字符串,返回数组中每个字符串之间都有一个空格。

                string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])"));
                

                首先获取枚举的值:

                var values = Enum.GetValues(typeof(Category));
                

                然后遍历值并使用上面的代码获取值:

                var ret = new Dictionary<int, string>();
                
                foreach (Category v in values)
                {
                   ret.Add((int)v, string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])")));
                } 
                

                就我而言,我需要一个包含值和显示名称的字典,这就是为什么我有变量“ret”

                【讨论】:

                  【解决方案14】:

                  根据Smac 的建议,我添加了一个扩展方法以方便使用,因为我看到很多人对此仍有疑问。

                  我使用了注解和辅助扩展方法。

                  枚举定义:

                  internal enum TravelClass
                  {
                      [Description("Economy With Restrictions")]
                      EconomyWithRestrictions,
                      [Description("Economy Without Restrictions")]
                      EconomyWithoutRestrictions
                  }
                  

                  扩展类定义:

                  internal static class Extensions
                  {
                      public static string ToDescription(this Enum value)
                      {
                          FieldInfo field = value.GetType().GetField(value.ToString());
                          DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                          return attribute == null ? value.ToString() : attribute.Description;
                      }
                  }
                  

                  使用枚举的示例:

                  var enumValue = TravelClass.EconomyWithRestrictions;
                  string stringValue = enumValue.ToDescription();
                  

                  这将返回Economy With Restrictions

                  希望这可以作为一个完整的例子帮助人们。再次感谢Smac 这个想法,我刚刚用扩展方法完成了它。

                  【讨论】:

                    【解决方案15】:

                    如果您不想编写手动注释,可以使用扩展方法,将空格添加到枚举名称:

                    using System.Text.RegularExpressions;
                    
                    public static partial class Extensions
                    {
                        public static string AddCamelSpace(this string str) => Regex.Replace(Regex.Replace(str,
                            @"([^_\p{Ll}])([^_\p{Ll}]\p{Ll})", "$1 $2"),
                            @"(\p{Ll})([^_\p{Ll}])"          , "$1 $2");
                        public static string ToCamelString(this Enum e) =>
                            e.ToString().AddCamelSpace().Replace('_', ' ');
                    }
                    

                    你可以这样使用:

                    enum StudentType
                    {
                        BCStudent,
                        OntarioStudent,
                        badStudent,
                        GoodStudent,
                        Medal_of_HonorStudent
                    }
                    
                    StudentType.BCStudent.ToCamelString(); // BC Student
                    StudentType.OntarioStudent.ToCamelString(); // Ontario Student
                    StudentType.badStudent.ToCamelString(); // bad Student
                    StudentType.GoodStudent.ToCamelString(); // Good Student
                    StudentType.Medal_of_HonorStudent.ToCamelString(); // Medal of Honor Student
                    

                    .NET fiddle

                    【讨论】:

                      【解决方案16】:

                      检索枚举值对我来说相当复杂,而枚举值与其名称不同。为此,我想使用一个带有 const 字段的类和一个包含所有这些字段的列表。使用此列表,我可以稍后检查以进行验证。

                      public class Status
                      {
                          public const string NOT_STARTED = "not started";
                          public const string IN_PROGRESS = "in progress";
                          public const string ON_HOLD = "on hold";
                          public const string COMPLETED = "completed";
                          public const string REFUSED = "refused";
                      
                          public static string[] List = new string[] {
                              NOT_STARTED,
                              IN_PROGRESS,
                              ON_HOLD,
                              COMPLETED,
                              REFUSED
                          };
                      }
                      
                      class TestClass { 
                          static void Main(string[] args) { 
                              var newStatus = "new status"
                              if (!Status.List.Contains(newStatus))
                              {
                                  // new status is not valid 
                              }
                              if (newStatus == Status.IN_PROGRESS)
                              {
                                  // new status in progress
                              }
                          } 
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2011-05-19
                        • 2018-04-16
                        • 2013-09-08
                        • 2022-01-17
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多