将字符串与C#中的枚举关联

时间:2009-08-10 04:51:43

标签: c# enums string

我在C#窗口工作... vs05 ......我想在枚举字符串上放置空间....我在下面做代码有这个.....我的问题是在选择一个值之后组合我怎么能得到这个值的索引号.....如果我去编辑模式然后我需要显示用户已经选择的值.....如何获得枚举选择值的基础上索引号

public enum States
{
  California,
  [Description("New Mexico")]
  NewMexico,
  [Description("New York")]
  NewYork,
  [Description("South Carolina")]
  SouthCarolina,
  Tennessee,
  Washington
}

public static string GetEnumDescription(Enum value)
{
   FieldInfo fi = value.GetType().GetField(value.ToString());

   DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                     typeof(DescriptionAttribute), false);

   if (attributes != null && attributes.Length > 0)
      return attributes[0].Description;
   else
      return value.ToString();
}

public static IEnumerable<T> EnumToList<T>()
{
    Type enumType = typeof(T);

    // Can't use generic type constraints on value types,
    // so have to do check like this
    if (enumType.BaseType != typeof(Enum))
       throw new ArgumentException("T must be of type System.Enum");

    Array enumValArray = Enum.GetValues(enumType);
    List<T> enumValList = new List<T>(enumValArray.Length);

    foreach (int val in enumValArray)
    {
       enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
    }

    return enumValList;
 }

 private void Form1_Load(object sender, EventArgs e)
 {
    //cboSurveyRemarksType = new ComboBox();
    cboSurveyRemarksType.Items.Clear();
    foreach (States state in EnumToList<States>())
    {
       cboSurveyRemarksType.Items.Add(GetEnumDescription(state));
    }
 }

3 个答案:

答案 0 :(得分:2)

  1. 您可以遍历可用的枚举(Enum.GetValues(enumType))并查看哪个具有所选的描述(不是最佳性能,但对于组合框可能并不重要)。
  2. 你可以创建自己的属性,并在那里有索引(在编码实践方面很丑陋)
  3. 如果要提高选项#1的性能,可以使用每个枚举的描述预先缓存Dictionary<String, Integer>对象,然后使用它。

答案 1 :(得分:1)

所以你有一个整数,你想将它转换回枚举类型?只是施展它。只要您没有在枚举声明中明确指定任何值,并且只要您获得的“索引”是基于0的,您应该能够:

States state = (States) stateIndex;

(请注意,通过正常的.NET命名约定,这应该称为State - 通常为标志保留复数。)

这个答案是基于您的问题的文本而不是您的代码 - 我在您的代码中看不到任何真正引用索引的内容。

答案 2 :(得分:0)

简单。您可以将选定的索引(这是一个整数)转换为States枚举。我编写了一个简单的测试方法,演示了一些使用枚举的例子,这些例子应该有助于清除这个概念:

private static void TestMethod()
    {
        foreach (States state in EnumToList<States>())
        {
            Console.Write(GetEnumDescription(state) + "\t");
            Int32 index = ((Int32)state);
            Console.Write(index.ToString() + "\t");
            States tempState = (States)index;
            Console.WriteLine(tempState.ToString());

        }
        Console.ReadLine();
    }

如果您不理解,将很乐意进一步澄清。