【问题标题】:Get any enum from ComboBox从 ComboBox 获取任何枚举
【发布时间】:2017-02-22 21:41:50
【问题描述】:

我正在使用 WPF(C#) 进行编程。我用这个函数填充了ComboBox

public static void PopulateComboBox(ComboBox cmb, Type type)
{
    foreach (string name in Enum.GetNames(type))
    {
        cmb.Items.Add(name);
    }
}

现在我需要这样的方法(如下图所示)来获取any enum 作为输出:

public static enum PopulateComboBox(ComboBox cmb, string nameOfEnum, Type type)
{

}

这样的函数怎么写?

【问题讨论】:

  • 你的意思是public static Enum...?不知道你在问什么,你的问题是什么?
  • 您不能返回enum。我认为你的意思是返回 Enum 类型的东西。
  • List<string> names = new List<string>();的目的是什么?
  • @KernelMode 感谢您的评论。我忘了删除这一行。

标签: c# types enums enumeration


【解决方案1】:

我会考虑直接将枚举值添加到组合框而不是它们的名称。

另一个选项是Enum.Parse(Type enumType, string value)

【讨论】:

    【解决方案2】:

    最后我在this page 找到了答案。我的回答是:

    public static T ToEnum<T>(this string value)
    {
        return (T) Enum.Parse(typeof(T), value, true);
    }
    

    比如我这样称呼它:

    BorderType borderType = ToEnum<BorderType>("Constant");
    

    其中BorderTypeenum(来自OpenCV);

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      相关资源
      最近更新 更多