簡體   English   中英

將字符串數組轉換為枚舉

[英]Convert string array to enum on the fly

我將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# myEnum地將myArray轉換為myEnum嗎? 謝謝。

當然! 這就是你所需要的:

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

您將要使用Enum.Parsehttp//msdn.microsoft.com/en-us/library/essfb559.aspx

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

您希望如何在陣列中使用它我認為可以滿足您的需求。

編輯:在任何可能的情況下,首先將您的適配器名稱作為枚舉存儲到您的陣列是否可行? 是否有某些原因數組必須是字符串?

如果您的源數據不是完全可靠的,您可能需要考慮使用TryParse()IsDefined()僅轉換實際可以解析的項目。

從字符串數組中獲取myEnums數組可以通過以下代碼執行:

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

請注意, IsDefined()僅適用於單個枚舉值。 如果您有[Flags]枚舉,組合將無法通過測試。

如果要獲取枚舉值的名稱,則不必使用Parse。 不要使用.ToString() ,而是使用它。 例如,如果我想返回Ethernet我會執行以下操作:

public enum myEnum
{
    Ethernet,
    Wireless,
    Bluetooth
}

在您的主類中添加以下代碼行:

var enumName = Enum.GetName(typeof(myEnum), 0); //Results = "Ethernet"

如果要枚舉Enum值,可以執行此操作以獲取值:

foreach (myEnum enumVals in Enum.GetValues(typeof(myEnum)))
{
    Console.WriteLine(enumVals);//if you want to check the output for example
}

在循環中為數組中的每個元素使用Enum.Parse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM