11

我将一个绑定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

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

是否可以使用 c# 即时转换myArray为?myEnum谢谢你。

4

5 回答 5

11

当然!这就是你所需要的:

IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));
于 2012-12-12T14:49:00.060 回答
4

如果您的源数据不是完全可靠的,您可能需要考虑仅转换可以实际解析的项目,使用TryParse()and IsDefined()

从字符串数组中获取 myEnums 数组可以通过以下代码执行:

myEnum [] myEnums = myArray
    .Where(c => Enum.IsDefined(typeof(myEnum), c))
    .Select(c => (myEnum)Enum.Parse(typeof(myEnum), c))
    .ToArray();

请注意,IsDefined()仅适用于单个枚举值。如果您有[Flags]枚举,则组合无法通过测试。

于 2017-02-14T14:33:58.127 回答
3

你会想要使用:http Enum.Parse: //msdn.microsoft.com/en-us/library/essfb559.aspx

MyProperty = (myEnum)Enum.Parse(typeof(myEnum), myArray[0]);

我猜你想如何将它与你的阵列一起使用取决于你的需要。

编辑:无论如何,首先将您的适配器名称作为枚举存储到您的数组中是否可行?数组必须是字符串有什么原因吗?

于 2012-12-12T14:32:09.990 回答
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
}
于 2012-12-12T14:50:35.787 回答
0

Enum.Parse在循环中用于数组中的每个元素。

于 2012-12-12T14:31:57.490 回答