在运行时将字符串数组转换为枚举类型

12

我正在像这样将enum绑定到属性网格:

public enum myEnum
{
    Ethernet,
    Wireless,
    Bluetooth
}

public class MyClass
{
    public MyClass()
    {
        MyProperty = MyEnum.Wireless;
    }

    [DefaultValue(MyEnum.Wireless)]
    public MyEnum MyProperty { get; set; }
}

public Form1()
{
    InitializeComponent();
    PropertyGrid pg = new PropertyGrid();
    pg.SelectedObject = new MyClass();
    pg.Dock = DockStyle.Fill;
    this.Controls.Add(pg);
}

我的问题:当程序在运行时,我从网络适配器获取数据。我读取网络适配器,然后将适配器名称存储到myArray中,如下所示:

我的问题:在程序运行时获取实时数据。我读取网络适配器并将适配器名称存储到myArray中。

string[] myArray = new string[] { };
myArray[0] = "Ethernet";
myArray[1] = "Wireless";
myArray[2] = "Bluetooth";

在C#中,是否可以即时将myArray转换为myEnum?谢谢。


你正在错误地分配 myArray[] 的值,为什么硬编码枚举值..? - MethodMan
5个回答

12

没问题!这就是你需要的:

IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));

1
实际上,你需要强制转换 IEnumerable<myEnum> items = myArray.Select(a => (myEnum) Enum.Parse(typeof(myEnum), a)); 否则你会得到编译器错误,因为 Enum.Parse() 返回一个对象。 - MarkG

5
如果您的源数据不是完全可靠的,则可以考虑仅转换可以实际解析的项,使用 TryParse()IsDefined()
从字符串数组获取 myEnums 数组可以使用以下代码执行:
myEnum [] myEnums = myArray
    .Where(c => Enum.IsDefined(typeof(myEnum), c))
    .Select(c => (myEnum)Enum.Parse(typeof(myEnum), c))
    .ToArray();

请注意,IsDefined() 仅适用于单个枚举值。如果您有一个带有 [Flags] 特性的枚举类型,组合将无法通过测试。

3
您需要使用 Enum.Parsehttp://msdn.microsoft.com/en-us/library/essfb559.aspx
如何将其与数组一起使用取决于您的需求。
编辑:有没有可能最初将适配器名称作为枚举存储到您的数组中?是否有某些原因要求该数组必须是字符串?

我想将myArray绑定到属性网格,并且在属性网格上,myArray看起来像listbox,就像将枚举类型绑定到属性网格时一样。这就是为什么我想将数组转换为枚举的原因。 - new bie
当你绑定一个数组 myEnum[] myArray = new [] {myEnum.Ethernet, myEnum.Wireless, myEnum.Bluetooth}; 时会发生什么? - Chris Sinclair
问题在于枚举类型从未存在。程序运行时,我会获取数据适配器名称并将其存储到字符串数组中。如果将字符串数组绑定到属性网格,则属性网格上将显示一个字符串集合编辑器,而我希望它像列表框一样显示在属性网格上。这就是为什么我想将字符串转换为枚举类型的原因。 - new bie

1

如果您想获取枚举值的名称,您不必使用 Parse。不要使用 .ToString(),请改用这个。例如,如果我想返回 Ethernet,我会执行以下操作:

public enum myEnum
{
    Ethernet,
    Wireless,
    Bluetooth
}

在你的主类中添加这行代码:
var enumName = Enum.GetName(typeof(myEnum), 0); //Results = "Ethernet"

如果您想枚举枚举值,可以使用以下代码获取这些值:
foreach (myEnum enumVals in Enum.GetValues(typeof(myEnum)))
{
    Console.WriteLine(enumVals);//if you want to check the output for example
}

0
在循环中使用 Enum.Parse 处理数组中的每个元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接