在大多数情况下,简单的转换就足够了。
但有时您只能在运行时获取类型。
来了Enum.ToObject
进入游戏。当您需要动态获取枚举值(或者可能附加到枚举值的元数据(属性))时,可以使用它。
这是一个简单的例子:
enum Color { Red = 1, Green, Blue }
enum Theme { Dark = 1, Light, NotSure }
public static void Main(string[] args)
{
var elements = new[]
{
new { Value = 1, Type = typeof(Color) },
new { Value = 2, Type = typeof(Theme) },
new { Value = 3, Type = typeof(Color) },
new { Value = 1, Type = typeof(Theme) },
new { Value = 2, Type = typeof(Color) },
};
foreach (var element in elements)
{
var enumValue = Enum.ToObject(element.Type, element.Value);
Console.WriteLine($"{element.Type.Name}({element.Value}) = {enumValue}");
}
}
输出是:
Color(1) = Red
Theme(2) = Light
Color(3) = Blue
Theme(1) = Dark
Color(2) = Green
有关枚举转换的更多信息 https://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp