【问题标题】:Specify Enum Type with String parameter使用字符串参数指定枚举类型
【发布时间】:2015-04-19 11:20:58
【问题描述】:

首先,如果这是一个重复的问题,我深表歉意。找了很久都没用。

假设我有两个枚举:

public enum Dogs
{
    Mastiff,
    Bulldog
}

public enum Cats
{
    Manx,
    Tiger
}

根据用户从 ComboBox 中选择的“Cats”或“Dogs”,我想用适当的 Enum 值填充另一个 ComboBox。这可以通过这样的方法来完成:

void PopulateComboBox<EnumType>(RadComboBox box, Enum displayUnits)
{
    // values and text derived from enumExtension methods
    foreach (Enum unit in Enum.GetValues(typeof(EnumType)))
    {
        var item = new RadComboBoxItem(unit.GetName(), unit.ToString());
        item.ToolTip = unit.GetDescription();
        if (displayUnits != null && unit.ToString() == displayUnits.ToString())
            item.Selected = true;
        box.Items.Add(item);
    }
}

如何从用户指定的字符串值中获取正确的 EnumType,以便我可以这样调用它(如果我可以指定 'displayUnits' 参数来强制进行所需的选择,则可以加分):

string choice = myComboBox.SelectedValue;
?? choiceAsAnEnumType = choice variable converted in some way ??
PopulateComboBox<choiceAsAnEnumType>(outputComboBox, null);

这个实现会很有用,因为我当前的项目中有大量的枚举。目前,我必须在各种情况下执行switch (choice) 并传入适当的枚举类型。

该方法的任何变化都是可以接受的,因为我绝不会被这种策略所束缚(在实施任何其他策略的时间之外)。

编辑:为了解释 TryParse/Parse 建议,我对从字符串中获取枚举值(Mastiff 或 Bulldog)不感兴趣;相反,我想从字符串中获得某种 Enum (Dogs or Cats) 的味道。 TryParse 需要提供的 T ,在我的情况下我不知道 T 。如果我误解了作为 TryParse 示例提供的方法,我深表歉意,我对 C# 和 ASP 整体还是比较陌生。

【问题讨论】:

  • Parse string to enum type的可能重复
  • 为什么不将枚举本身添加到组合框中(而不是调用unit.GetName),然后您可以通过SelectedItem 属性而不是SelectedValue 属性访问它?
  • @christophano 因为我不知道你可以这样做,哈哈。看起来我将不得不在周末做一些工作来测试这些东西。感谢您的回复。
  • @chomba 我很确定 TryParse 用于根据字符串从枚举中获取值。至少这是我从那个例子中得到的。

标签: c# asp.net enums


【解决方案1】:

您可以像这样从字符串加载类型以传递给您的方法。您不会在 populate 方法上使用泛型。

class AnimalOptions
{
    public enum Dogs
    {
        Mastiff,
        Bulldog
    }

    public enum Cats
    {
        Manx,
        Tiger
    }
}


Type t = typeof(AnimalOptions);
Type enumType = t.GetNestedType("Dogs");
Populate(enumType);

【讨论】:

  • 有没有办法做到这一点而不将它们全部包装在一个类中?目前它们都只是单独的文件(Dogs.cs、Cats.cs 等)。虽然如果没有,我会试一试。复制/粘贴枚举不需要太多努力。
  • 如果想从当前程序集中加载反射,可以使用反射。 Assembly.GetExecutingAssembly().GetTypes().First(x =&gt; x.Name == "Dogs");
  • 哦,很好。反射方法在加载时间上是否会更加繁重?
  • 反射速度较慢,但​​我会测试它对您和您的用例的执行情况。我个人没有遇到性能问题。
【解决方案2】:

我会用这样的枚举类型加载你的第一个组合框:

firstComboBox.Items.Add(new RadComboBoxItem(typeof(Dogs), typeof(Dogs).Name));
firstComboBox.Items.Add(new RadComboBoxItem(typeof(Cats), typeof(Cats).Name));

然后,从第一个组合框上的选定项目更改事件中调用:

secondComboBox.Items.Clear();
foreach (var value in Enum.GetValues(firstComboBox.SelectedValue))
{
    secondComboBox.Items.Add(new RadComboBoxItem(value, value.ToString()));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多