【问题标题】:How to define an enum with string value?如何用字符串值定义枚举?
【发布时间】:2012-01-25 04:19:26
【问题描述】:

我正在尝试定义 Enum 并添加在 CSV 或类似文件中使用的有效常用分隔符。然后我将把它绑定到ComboBox 作为数据源,这样每当我从 Enum 定义中添加或删除时,我都不需要更改组合框中的任何内容。

问题是如何用字符串表示来定义枚举,例如:

public enum SeparatorChars{Comma = ",", Tab = "\t", Space = " "}

【问题讨论】:

标签: c# string enums


【解决方案1】:

也许为时已晚,但它已经过去了。

我们可以使用属性 EnumMember 来管理 Enum 值。

public enum UnitOfMeasure
{
    [EnumMember(Value = "KM")]
    Kilometer,
    [EnumMember(Value = "MI")]
    Miles
}

这样,UnitOfMeasure 的结果值将是 KM 或 MI。这也可以在 Andrew Whitaker answer 中看到。

【讨论】:

  • 最佳和最简单的答案。完美运行
【解决方案2】:

您可以实现它,但需要一些工作。

  1. 定义一个包含枚举字符串值的属性类。

  2. 定义一个从属性返回值的扩展方法。例如..GetStringValue(this Enum value) 将返回属性值。

  3. 然后你可以像这样定义枚举..

    public enum Test : int {
        [StringValue("a")]
        Foo = 1,
        [StringValue("b")]
        Something = 2        
    } 
    
  4. 从属性Test.Foo.GetStringValue()中取回值;

参考:Enum With String Values In C#

【讨论】:

  • 我知道这很旧,但它显然是独一无二的,它允许您在代码中使用枚举并在数据库中使用字符串值。太棒了
  • 另一个迟到的评论,但这确实是一个绝妙的解决方案
  • 请记住反射对性能的影响,如果这与您的情况相关。
  • 绝对惊人的答案!喜欢简单的实现。
  • 仅供参考,我多年前在 Nuget 包中实现了这个确切的解决方案,因此您可以 JustUseIt 而不必担心实现支持属性和访问器方法(另外我添加了一些性能改进和一些额外的花里胡哨) :D Nuget 包:nuget.org/packages/EnumStringValues
【解决方案3】:

添加更多内容,因为这里的一些答案缺少使用枚举的意义。自然,一种选择是将明确定义的字符串作为静态变量等,但随后您也会为非法值打开接口,即您需要验证输入。使用枚举可以保证只有允许的值被传递到您的接口。

enum Separator
{
    Comma,
    Tab,
    Space,
    CRLF,
    SoFunny
}

除此之外,您还可以使用例如用于映射目的的内部字典。

    private readonly Dictionary<Separator, string> separatorMap = new Dictionary<Separator, string>()
    {
        { Separator.Comma, "," },
        { Separator.Tab, "\t" },
        { Separator.Space, " " },
        { Separator.CRLF, "\r\n" },
        { Separator.SoFunny, "Your Mom" }
    };

更复杂的方法是创建一个static class 为枚举提供新功能并在那里处理映射。

使用上述代码的示例如下。

public string TransformToSingleString(List<string> values, Separator separator)
{
    var separateWith = separatorMap[separator];
    ...
}

【讨论】:

    【解决方案4】:

    我希望有一个更优雅的解决方案,比如在语言级别只允许字符串类型enum,但似乎还不支持。下面的代码与其他答案的思路基本相同,但我认为它更短,可以重复使用。您所要做的就是在每个 enum 条目上方添加一个 [Description("")] 并添加一个有 10 行的类。

    班级:

    public static class Extensions
    {
        public static string ToStringValue(this Enum en)
        {
            var type = en.GetType();
            var memInfo = type.GetMember(en.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            var stringValue = ((DescriptionAttribute)attributes[0]).Description;
            return stringValue;
        }
    }
    

    用法:

        enum Country
        {
            [Description("Deutschland")]
            Germany,
            [Description("Nippon")]
            Japan,
            [Description("Italia")]
            Italy,
        }
    
        static void Main(string[] args)
        {
            Show(new[] {Country.Germany, Country.Japan, Country.Italy});
    
            void Show(Country[] countries)
            {
                foreach (var country in countries)
                {
                    Debug.WriteLine(country.ToStringValue());
                }
            }
        }
    

    【讨论】:

      【解决方案5】:

      我创建了一个基类,用于在 .NET 中创建字符串值枚举。它只是一个 C# 文件,您可以将其复制并粘贴到您的项目中,或通过名为 StringEnum 的 NuGet 包安装。

      用法:

      ///<completionlist cref="HexColor"/> 
      class HexColor : StringEnum<HexColor>
      {
          public static readonly HexColor Blue = New("#FF0000");
          public static readonly HexColor Green = New("#00FF00");
          public static readonly HexColor Red = New("#000FF");
      }
      

      特点

      • 您的 StringEnum 看起来有点类似于常规枚举:
          // Static Parse Method
          HexColor.Parse("#FF0000") // => HexColor.Red
          HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
          HexColor.Parse("invalid") // => throws InvalidOperationException
      
          // Static TryParse method.
          HexColor.TryParse("#FF0000") // => HexColor.Red
          HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
          HexColor.TryParse("invalid") // => null
      
          // Parse and TryParse returns the preexistent instances
          object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true
      
          // Conversion from your `StringEnum` to `string`
          string myString1 = HexColor.Red.ToString(); // => "#FF0000"
          string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
      
      • 如果类使用 xml 注释 &lt;completitionlist&gt; 进行注释,Intellisense 将建议枚举名称。 (适用于 C# 和 VB):即

      安装

      要么:

      • 安装最新的StringEnum NuGet 包,它基于.Net Standard 1.0,因此它在.Net Core >= 1.0、.Net Framework >= 4.5、Mono >= 4.6 等上运行。
      • 或将以下 StringEnum 基类粘贴到您的项目中。 (latest version)
          public abstract class StringEnum<T> : IEquatable<T> where T : StringEnum<T>, new()
          {
              protected string Value;
              private static IList<T> valueList = new List<T>();
              protected static T New(string value)
              {
                  if (value == null)
                      return null; // the null-valued instance is null.
      
                  var result = new T() { Value = value };
                  valueList.Add(result);
                  return result;
              }
      
              public static implicit operator string(StringEnum<T> enumValue) => enumValue.Value;
              public override string ToString() => Value;
      
              public static bool operator !=(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value != o2?.Value;
              public static bool operator ==(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value == o2?.Value;
      
              public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
              bool IEquatable<T>.Equals(T other) => this.Value.Equals(other.Value);
              public override int GetHashCode() => Value.GetHashCode();
      
              /// <summary>
              /// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else throws InvalidOperationException.
              /// </summary>
              /// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
              /// <param name="caseSensitive">If true, the strings must match case sensitivity.</param>
              public static T Parse(string value, bool caseSensitive = false)
              {
                  var result = TryParse(value, caseSensitive);
                  if (result == null)
                      throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
      
                  return result;
              }
      
              /// <summary>
              /// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else returns null.
              /// </summary>
              /// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
              /// <param name="caseSensitive">If true, the strings must match case sensitivity.</param>
              public static T TryParse(string value, bool caseSensitive = false)
              {
                  if (value == null) return null;
                  if (valueList.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
                  var field = valueList.FirstOrDefault(f => f.Value.Equals(value,
                          caseSensitive ? StringComparison.Ordinal
                                        : StringComparison.OrdinalIgnoreCase));
                  // Not using InvariantCulture because it's only supported in NETStandard >= 2.0
      
                  if (field == null)
                      return null;
      
                  return field;
              }
          }
      
      • 对于Newtonsoft.Json 序列化支持,请复制此扩展版本。 StringEnum.cs

      我意识到这段代码与 Ben 的答案相似。我真诚地从头开始写它。但是我认为它有一些额外的东西,比如&lt;completitionlist&gt; hack,生成的类看起来更像一个 Enum,没有使用 Parse() 上的反射,我希望在其中解决传入问题和反馈的 NuGet 包和 repo。

      【讨论】:

        【解决方案6】:

        我最近开始做的是使用Tuples

        public static (string Fox, string Rabbit, string Horse) Animals = ("Fox", "Rabbit", "Horse");
        ...
        public static (string Comma, string Tab, string Space) SeparatorChars = (",", "\t", " ");
        

        【讨论】:

        • 聪明!虽然,我不能立即看到使用结构或类的好处——我错过了什么吗?我喜欢它,但可能不会使用它,因为我发现它更难阅读。不过谢谢!
        • 我想它很简洁,如果只是用于私有代码/少量值,则值得使用。
        【解决方案7】:

        它对我有用..

           public class ShapeTypes
            {
                private ShapeTypes() { }
                public static string OVAL
                {
                    get
                    {
                        return "ov";
                    }
                    private set { }
                }
        
                public static string SQUARE
                {
                    get
                    {
                        return "sq";
                    }
                    private set { }
                }
        
                public static string RECTANGLE
                {
                    get
                    {
                        return "rec";
                    }
                    private set { }
                }
            }
        

        【讨论】:

          【解决方案8】:

          如果您希望代码看起来像enum,则可以扩展静态类概念。

          当您尚未最终确定您想要的enum names 并且enum valuesstringenam name 表示时,以下方法有效;使用nameof() 让你的重构更简单。

          public static class Colours
          {
              public static string Red => nameof(Red);
              public static string Green => nameof(Green);
              public static string Blue => nameof(Blue);
          }
          

          这样就达到了枚举有字符串值的目的(比如下面的伪代码):

          public enum Colours
          {
              "Red",
              "Green",
              "Blue"
          }
          

          【讨论】:

            【解决方案9】:

            基于此处的一些答案,我实现了一个可重用的基类,它模仿枚举的行为,但使用 string 作为底层类型。它支持各种操作,包括:

            1. 获取可能值列表
            2. 转换为字符串
            3. 通过.Equals==!= 与其他实例进行比较
            4. 使用 JSON.NET JsonConverter 与 JSON 进行转换

            这是整个基类:

            public abstract class StringEnumBase<T> : IEquatable<T>
                where T : StringEnumBase<T>
            {
                public string Value { get; }
            
                protected StringEnumBase(string value) => this.Value = value;
            
                public override string ToString() => this.Value;
            
                public static List<T> AsList()
                {
                    return typeof(T)
                        .GetProperties(BindingFlags.Public | BindingFlags.Static)
                        .Where(p => p.PropertyType == typeof(T))
                        .Select(p => (T)p.GetValue(null))
                        .ToList();
                }
            
                public static T Parse(string value)
                {
                    List<T> all = AsList();
            
                    if (!all.Any(a => a.Value == value))
                        throw new InvalidOperationException($"\"{value}\" is not a valid value for the type {typeof(T).Name}");
            
                    return all.Single(a => a.Value == value);
                }
            
                public bool Equals(T other)
                {
                    if (other == null) return false;
                    return this.Value == other?.Value;
                }
            
                public override bool Equals(object obj)
                {
                    if (obj == null) return false;
                    if (obj is T other) return this.Equals(other);
                    return false;
                }
            
                public override int GetHashCode() => this.Value.GetHashCode();
            
                public static bool operator ==(StringEnumBase<T> a, StringEnumBase<T> b) => a?.Equals(b) ?? false;
            
                public static bool operator !=(StringEnumBase<T> a, StringEnumBase<T> b) => !(a?.Equals(b) ?? false);
            
                public class JsonConverter<T> : Newtonsoft.Json.JsonConverter
                    where T : StringEnumBase<T>
                {
                    public override bool CanRead => true;
            
                    public override bool CanWrite => true;
            
                    public override bool CanConvert(Type objectType) => ImplementsGeneric(objectType, typeof(StringEnumBase<>));
            
                    private static bool ImplementsGeneric(Type type, Type generic)
                    {
                        while (type != null)
                        {
                            if (type.IsGenericType && type.GetGenericTypeDefinition() == generic)
                                return true;
            
                            type = type.BaseType;
                        }
            
                        return false;
                    }
            
                    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
                    {
                        JToken item = JToken.Load(reader);
                        string value = item.Value<string>();
                        return StringEnumBase<T>.Parse(value);
                    }
            
                    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
                    {
                        if (value is StringEnumBase<T> v)
                            JToken.FromObject(v.Value).WriteTo(writer);
                    }
                }
            }
            

            这就是实现“字符串枚举”的方式:

            [JsonConverter(typeof(JsonConverter<Colour>))]
            public class Colour : StringEnumBase<Colour>
            {
                private Colour(string value) : base(value) { }
            
                public static Colour Red => new Colour("red");
                public static Colour Green => new Colour("green");
                public static Colour Blue => new Colour("blue");
            }
            

            可以这样使用:

            public class Foo
            {
                public Colour colour { get; }
            
                public Foo(Colour colour) => this.colour = colour;
            
                public bool Bar()
                {
                    if (this.colour == Colour.Red || this.colour == Colour.Blue)
                        return true;
                    else
                        return false;
                }
            }
            

            我希望有人觉得这很有用!

            【讨论】:

              【解决方案10】:

              现在回答有点晚了,但也许它可以帮助将来的人。我发现使用 struct 来解决这类问题更容易。

              以下示例是从 MS 代码中复制粘贴的部分:

              namespace System.IdentityModel.Tokens.Jwt
              {
                  //
                  // Summary:
                  //     List of registered claims from different sources http://tools.ietf.org/html/rfc7519#section-4
                  //     http://openid.net/specs/openid-connect-core-1_0.html#IDToken
                  public struct JwtRegisteredClaimNames
                  {
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string Actort = "actort";
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string Typ = "typ";
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string Sub = "sub";
                      //
                      // Summary:
                      //     http://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
                      public const string Sid = "sid";
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string Prn = "prn";
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string Nbf = "nbf";
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string Nonce = "nonce";
                      //
                      // Summary:
                      //     http://tools.ietf.org/html/rfc7519#section-4
                      public const string NameId = "nameid";
              
                  }
              }
              

              【讨论】:

              • 你能解释一下为什么这种方法比使用类更好吗?
              • @GerardoGrignoli 我不完全知道他们为什么在 MS 中使用 struct 而不是 class 来处理这种事情。我什至没有试图找出答案,因为这对我来说非常有用。也许尝试在堆栈上提问...
              • 一个结构实际上应该只用于表示单个值,小于 16 个字节,是不可变的,并且不必经常拆箱。这个答案不符合标准,应该是一个类。来源:docs.microsoft.com/en-us/dotnet/standard/design-guidelines/…
              • @JMD 1. 此代码是从 .NET 复制粘贴的。 2. 代表单一值,不可变,不拆箱。 3. 它可能不低于 16B,但考虑到它的使用方式,我不认为这是一个问题。
              • 我知道它是从旧示例中复制/粘贴的。我只是提供新的指导方针,所以人们并不认为这些信息仍然是正确的。请参阅我上面提供的链接,了解有关此答案为何不符合当前准则的更多信息。
              【解决方案11】:

              模拟枚举行为但使用string 而不是int 的类可以按如下方式创建...

              public class GrainType
              {
                  private string _typeKeyWord;
              
                  private GrainType(string typeKeyWord)
                  {
                      _typeKeyWord = typeKeyWord;
                  }
              
                  public override string ToString()
                  {
                      return _typeKeyWord;
                  }
              
                  public static GrainType Wheat = new GrainType("GT_WHEAT");
                  public static GrainType Corn = new GrainType("GT_CORN");
                  public static GrainType Rice = new GrainType("GT_RICE");
                  public static GrainType Barley = new GrainType("GT_BARLEY");
              
              }
              

              用法...

              GrainType myGrain = GrainType.Wheat;
              
              PrintGrainKeyword(myGrain);
              

              那么……

              public void PrintGrainKeyword(GrainType grain) 
              {
                  Console.Writeline("My Grain code is " + grain.ToString());   // Displays "My Grain code is GT_WHEAT"
              }
              

              【讨论】:

              • 例如,你不能做GrainType myGrain = "GT_CORN"
              • 你可以覆盖操作符
              【解决方案12】:

              对于字符串值的简单枚举(或任何其他类型):

              public static class MyEnumClass
              {
                  public const string 
                      MyValue1 = "My value 1",
                      MyValue2 = "My value 2";
              }
              

              用法:string MyValue = MyEnumClass.MyValue1;

              【讨论】:

              • 虽然这不是枚举,但我认为这可能会为用户尝试做的事情提供最佳解决方案。有时,最简单的解决方案是最好的。
              【解决方案13】:

              我们不能将枚举定义为字符串类型。允许的枚举类型为 byte、sbyte、short、ushort、int、uint、long 或 ulong。

              如果您需要有关枚举的更多详细信息,请点击以下链接,该链接将帮助您了解枚举。 Enumeration

              @narendras1414

              【讨论】:

                【解决方案14】:

                枚举类

                 public sealed class GenericDateTimeFormatType
                    {
                
                        public static readonly GenericDateTimeFormatType Format1 = new GenericDateTimeFormatType("dd-MM-YYYY");
                        public static readonly GenericDateTimeFormatType Format2 = new GenericDateTimeFormatType("dd-MMM-YYYY");
                
                        private GenericDateTimeFormatType(string Format)
                        {
                            _Value = Format;
                        }
                
                        public string _Value { get; private set; }
                    }
                

                枚举消耗

                public static void Main()
                {
                       Country A = new Country();
                
                       A.DefaultDateFormat = GenericDateTimeFormatType.Format1;
                
                      Console.ReadLine();
                }
                

                【讨论】:

                  【解决方案15】:

                  据我所知,您不会被允许将字符串值分配给枚举。你可以做的是创建一个包含字符串常量的类。

                  public static class SeparatorChars
                  {
                      public static String Comma { get { return ",";} } 
                      public static String Tab { get { return "\t,";} } 
                      public static String Space { get { return " ";} } 
                  }
                  

                  【讨论】:

                  • 这种方法与其他方法相反的缺点是,如果不做一些额外/特殊的事情,你就无法枚举这些。
                  • 这无助于在编译期间强制执行某些值,因为 separator 现在是一个字符串(可以是任何东西)而不是具有受限有效值的 Separator 类型。
                  【解决方案16】:

                  虽然实际上不可能使用charstring 作为枚举的基础,但我认为这不是您真正喜欢做的事情。

                  就像您提到的那样,您希望有一个可能性的枚举,并在组合框中显示一个字符串表示形式。如果用户选择这些字符串表示之一,您希望得到相应的枚举。这是可能的:

                  首先我们必须将一些字符串链接到一个枚举值。这可以通过使用DescriptionAttribute 来完成,就像在herehere 中所描述的那样。

                  现在您需要创建一个枚举值列表和相应的描述。这可以通过使用以下方法来完成:

                  /// <summary>
                  /// Creates an List with all keys and values of a given Enum class
                  /// </summary>
                  /// <typeparam name="T">Must be derived from class Enum!</typeparam>
                  /// <returns>A list of KeyValuePair&lt;Enum, string&gt; with all available
                  /// names and values of the given Enum.</returns>
                  public static IList<KeyValuePair<T, string>> ToList<T>() where T : struct
                  {
                      var type = typeof(T);
                  
                      if (!type.IsEnum)
                      {
                          throw new ArgumentException("T must be an enum");
                      }
                  
                      return (IList<KeyValuePair<T, string>>)
                              Enum.GetValues(type)
                                  .OfType<T>()
                                  .Select(e =>
                                  {
                                      var asEnum = (Enum)Convert.ChangeType(e, typeof(Enum));
                                      return new KeyValuePair<T, string>(e, asEnum.Description());
                                  })
                                  .ToArray();
                  }
                  

                  现在您将获得所有枚举及其描述的键值对列表。因此,让我们简单地将其指定为组合框的数据源。

                  var comboBox = new ComboBox();
                  comboBox.ValueMember = "Key"
                  comboBox.DisplayMember = "Value";
                  comboBox.DataSource = EnumUtilities.ToList<Separator>();
                  
                  comboBox.SelectedIndexChanged += (sender, e) =>
                  {
                      var selectedEnum = (Separator)comboBox.SelectedValue;
                      MessageBox.Show(selectedEnum.ToString());
                  }
                  

                  用户会看到枚举的所有字符串表示形式,并且在您的代码中您将获得所需的枚举值。

                  【讨论】:

                    【解决方案17】:

                    你不能,因为 enum 只能基于原始数字类型。 您可以尝试改用Dictionary

                    Dictionary<String, char> separators = new Dictionary<string, char>
                    {
                        {"Comma", ','}, 
                        {"Tab",  '\t'}, 
                        {"Space", ' '},
                    };
                    

                    或者,您可以使用Dictionary&lt;Separator, char&gt;Dictionary&lt;Separator, string&gt;,其中Separator 是普通枚举:

                    enum Separator
                    {
                        Comma,
                        Tab,
                        Space
                    }
                    

                    这会比直接处理字符串更令人愉快。

                    【讨论】:

                      【解决方案18】:

                      首先你尝试分配字符串而不是字符,即使它们只是一个字符。使用“,”代替“,”。接下来的事情是,枚举只采用没有char 的整数类型,你可以使用 unicode 值,但我强烈建议你不要这样做。 如果您确定这些值在不同的文化和语言中保持不变,我会使用带有 const 字符串的静态类。

                      【讨论】:

                        【解决方案19】:

                        你不能 - 枚举值必须是整数值。您可以使用属性将字符串值与每个枚举值相关联,或者在这种情况下,如果每个分隔符都是单个字符,您可以只使用 char 值:

                        enum Separator
                        {
                            Comma = ',',
                            Tab = '\t',
                            Space = ' '
                        }
                        

                        (编辑:只是为了澄清,你不能使char成为枚举的基础类型,但你可以使用char常量来分配每个枚举值对应的整数值。上面的基础类型枚举是int。)

                        如果你需要的话,那么一个扩展方法:

                        public string ToSeparatorString(this Separator separator)
                        {
                            // TODO: validation
                            return ((char) separator).ToString();
                        }
                        

                        【讨论】:

                        • 字符在枚举中无效。 Msdn:“每个枚举类型都有一个底层类型,可以是除 char 之外的任何整数类型。”
                        • @dowhilefor:根据我的回答,您可以为 value 使用字符文字。我测试了它:)
                        • 因为此要求适用于文件,用户可能需要 CRLF 分隔符。它也适用于这种情况吗?
                        • @JonSkeet 哦,你是对的,当然可以将它们转换为 int。没关系。
                        • @ShaunLuttin:枚举只是“命名数字”——所以字符串枚举根本不适合该模型。
                        【解决方案20】:

                        你不能用枚举做到这一点,但你可以这样做:

                        public static class SeparatorChars
                        {
                            public static string Comma = ",";
                        
                            public static string Tab = "\t";
                        
                            public static string Space = " ";
                        }
                        

                        【讨论】:

                        • +1 虽然我认为这是正确的解决方案,但我会更改类的名称或将类型更改为字符。只是为了保持一致。
                        • 谢谢,在这种情况下,您能说出与comboBox.DataSource = Enum.GetValues(typeof(myEnum)); 等效的内容吗?
                        • @Sean87:我想要那个,我会接受 JonSkeets 的回答。
                        • 我认为这几乎是正确的答案,因为它在 switch-case 块中不可用。字段应为const 以便。不过想Enum.GetValues(typeof(myEnum))还是没办法。
                        • 我会使用const 而不是static。常量是只读的和静态的,在构造函数中不可赋值(除非是只读字段)。
                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2021-12-23
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2014-07-23
                        相关资源
                        最近更新 更多