将String转换为Enum而不知道它在C#中的类型

时间:2012-05-24 12:27:32

标签: c# enums

我遇到了问题。我在我的应用程序中设置了一些枚举。像

public enum EnmSection
{
    Section1,
    Section2,
    Section3
}

public enum Section1
{
    TestA,
    TestB
}

public enum Section2
{
    Test1,
    Test2
}

EnmSection是主要枚举,其中包含在其下面声明的其他枚举(作为字符串)。现在我必须在下拉列表中填写EnmSection的值。我已经完成了。 像这样......

drpSectionType.DataSource = Enum.GetNames(typeof(EnmSection));
drpSectionType.DataBind();

现在,我的下拉菜单值为Section1,Section2,Section3

问题是:

我还有另一个下拉列表drpSubSection。现在我想填写这个下拉列表,无论我在drpSectionType中选择了什么。

for ex如果我在drpSectionType中选择了Section1,那么drpSubsection应该包含该值 TestA,TestB。像这样:

protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e)
{
    string strType = drpSectionType.SelectedValue;
    drpSubsection.DataSource = Enum.GetNames(typeof());
    drpSubsection.DataBind();
}

这里typeof()期待enum.But我将选中的值作为字符串。我怎样才能实现这一功能。

由于

4 个答案:

答案 0 :(得分:3)

如果引用包含另一个名为Section1的值的枚举的程序集

,该怎么办?

你只需要尝试所有你关心的枚举,一次一个,看看哪个有效。您可能想要使用Enum.TryParse

答案 1 :(得分:0)

drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType));

如果枚举位于另一个程序集中(即它们不在mscorlib或当前程序集中),则需要提供AssemblyQualifiedName。最简单的方法是查看typeof(Section1).AssemblyQualifiedName,然后修改代码以包含所有必要的部分。完成后代码看起来像这样:

drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType + ", MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089"));

答案 2 :(得分:0)

这样的东西可能有用,但你必须做一些异常处理:

protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e) 
{    
  string strType = drpSectionType.SelectedValue;    
  EnmSection section = (EnmSection)Enum.Parse(typeof(EnmSection), strType);
  drpSubsection.DataSource = Enum.GetNames(typeof(section));     
  drpSubsection.DataBind();

 }

答案 3 :(得分:0)

这可能有点过头,但是如果你将IEnumItem的绑定数组绑定到你的下拉菜单并将其设置为显示它们的显示文本,它就会有效。

public interface IEnumBase
{
  IEnumItem[] Items { get; }
}

public interface IEnumItem : IEnumBase
{
  string DisplayText { get; }
}

public class EnumItem : IEnumItem
{
  public string DisplayText { get; set; }
  public IEnumItem[] Items { get; set; }
}

public class EnmSections : IEnumBase
{
  public IEnumItem[] Items { get; private set; }

  public EnmSections()
  {
    Items = new IEnumItem[]
    {
      new EnumItem
      {
        DisplayText = "Section1",
        Items = new IEnumItem[]
        {
          new EnumItem { DisplayText = "TestA" },
          new EnumItem { DisplayText = "TestB" }
        }
      },
      new EnumItem
      {
        DisplayText = "Section2",
        Items = new IEnumItem[]
        {
          new EnumItem { DisplayText = "Test1" },
          new EnumItem { DisplayText = "Test2" }
        }
      }
    };
  }
}