问题
I am binding an enum
to a property grid like this:
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);
}
My problem: I get data on the fly when the program is running. I read the network adapter then store adapter names to myArray
like this:
string[] myArray = new string[] { };
myArray[0] = "Ethernet";
myArray[1] = "Wireless";
myArray[2] = "Bluetooth";
Is possible convert myArray
to myEnum
on the fly using c#? Thank You.
回答1:
Sure! This is all you need:
IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));
回答2:
You'll want to use Enum.Parse
: http://msdn.microsoft.com/en-us/library/essfb559.aspx
MyProperty = (myEnum)Enum.Parse(typeof(myEnum), myArray[0]);
How you'll want to use that with your array I guess is up to your needs.
EDIT: By any chance, is it feasible to store your adapter names to your array as enumerations in the first place? Is there some reason the array must be strings?
回答3:
If your source data is not something entirely reliable, you may want to consider converting only the items that can actually be parsed, using TryParse()
and IsDefined()
.
Getting an array of myEnums from an array of strings can be performed by the following code:
myEnum [] myEnums = myArray
.Where(c => Enum.IsDefined(typeof(myEnum), c))
.Select(c => (myEnum)Enum.Parse(typeof(myEnum), c))
.ToArray();
Note that IsDefined()
only works with a single enumerated value. If you have a [Flags]
enum, combinations fail the test.
回答4:
You do not have to use Parse if you want to get the name of the enum's value. Don't use .ToString()
, use this instead. For example if I want to return Ethernet
I would do the following:
public enum myEnum
{
Ethernet,
Wireless,
Bluetooth
}
In your main class add this line of code:
var enumName = Enum.GetName(typeof(myEnum), 0); //Results = "Ethernet"
If you want to enumerate over the Enum Values you could do this to get the values:
foreach (myEnum enumVals in Enum.GetValues(typeof(myEnum)))
{
Console.WriteLine(enumVals);//if you want to check the output for example
}
回答5:
Use Enum.Parse
in the loop for each element in the array.
来源:https://stackoverflow.com/questions/13841880/convert-string-array-to-enum-on-the-fly