Microsoft Docs Enum.TryParse<TEnum>(String, TEnum) 将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。 用于指示转换是否成功的返回值
https://learn.microsoft.com/zh-cn/dotnet/api/system.enum.tryparse?view=net-7.0#system-enum-tryparse-1(system-string-0@)
官方示例:
[C#] 纯文本查看 复制代码
using System;
[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
public static void Main()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
Colors colorValue;
if (Enum.TryParse(colorString, out colorValue))
if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
else
Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
}
}
}
// The example displays the following output:
// Converted '0' to None.
// Converted '2' to Green.
// 8 is not an underlying value of the Colors enumeration.
// blue is not a member of the Colors enumeration.
// Converted 'Blue' to Blue.
// Yellow is not a member of the Colors enumeration.
// Converted 'Red, Green' to Red, Green.
我个人比较喜欢有泛型的, 强类型应该能确定就确定, 一般情况下我不用有type类型参数的相关重载. |