gpt4 book ai didi

c# - 如何在 C# 中将 int 转换为枚举?

转载 作者:IT王子 更新时间:2023-10-29 03:26:47 26 4
gpt4 key购买 nike

如何在 C# 中将 int 转换为 enum

最佳答案

来自一个整数:

YourEnum foo = (YourEnum)yourInt;

来自字符串:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}

来自一个数字:

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);

关于c# - 如何在 C# 中将 int 转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com