C# String 和 enum 相互轉換 示範

建立範例列舉(enum):
    
public enum IceLevel
{
    None,
    Little,
    Less,
    Normal,
    More,
}
    

列舉轉換為字串

要將列舉轉換為字串非常簡單,只要使用 ToString() 方法即可,在字串中使用字串差補的方式則是會自動轉換:
    
string typeString = IceLevel.Normal.ToString();
Console.WriteLine($"type: {typeString}");

Console.WriteLine($"type: {IceLevel.Normal}");
    

字串轉換為列舉

Enum.Parse

將字串轉換為列舉 :
    
string str = "Normal";
IceLevel type = (IceLevel)Enum.Parse(typeof(IceLevel), str);

Console.WriteLine($"type: {type}"); // type: Normal
    

上方的轉換會區分大小寫,如果大小寫不一致則會拋出下面的例外:
    
Unhandled exception. System.ArgumentException: Requested value 'normal' was not found.
   at System.Enum.TryParseByName(RuntimeType enumType, ReadOnlySpan`1 value, Boolean ignoreCase, Boolean throwOnFailu
re, UInt64& result)
   at System.Enum.TryParseInt32Enum(RuntimeType enumType, ReadOnlySpan`1 value, Int32 minInclusive, Int32 maxInclusiv
e, Boolean ignoreCase, Boolean throwOnFailure, TypeCode type, Int32& result)
   at System.Enum.TryParse(Type enumType, ReadOnlySpan`1 value, Boolean ignoreCase, Boolean throwOnFailure, Object& r
esult)
   at System.Enum.Parse(Type enumType, String value)
   at Program.<Main>$(String[] args) in C:\Users\ruyut\Documents\RiderProjects\2023\test\ConsoleAppEnumTest\ConsoleAp
pEnumTest\Program.cs:line 4
    

如果需要忽略大小寫可以在 Enum.Parse 多傳入一個 boolean 參數:
    
string str = "normal";
IceLevel type = (IceLevel)Enum.Parse(typeof(IceLevel), str, true);

Console.WriteLine($"type: {type}"); // type: Normal
    

使用 Enum.Parse 在無法將字串轉換為列舉時會拋出例外,如果不想要讓他拋出例外也可以使用 Enum.TryParse

Enum.TryParse

    
string str = "Normal";

if (!Enum.TryParse<IceLevel>(str, out var type))
{
    // todo: 處理轉換失敗
    Console.WriteLine($"Failed to parse {str} to {nameof(IceLevel)}");
}

Console.WriteLine($"type: {type}");
    

常見的方式會是使用 Enum.TryParse 判斷是否轉換成功,如果轉換失敗則會拋出自訂例外,成功則讀取 Enum.TryParse 傳出的 type 方法

Enum.TryParse 也可以忽略大小寫,寫法則是將 boolean 放在第二個參數:
    
string str = "normal";

if (!Enum.TryParse<IceLevel>(str, true, out var type))
{
    // todo: 處理轉換失敗
    Console.WriteLine($"Failed to parse {str} to {nameof(IceLevel)}");
}

Console.WriteLine($"type: {type}");
    



參考資料:
Microsoft.Learn - Enum.Parse
Microsoft.Learn - Enum.TryParse
Microsoft.Learn - String interpolation using $

留言