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

标签 c# enums casting integer

如何在 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/

相关文章:

c# - C# 中二进制文件的读写

c# - 我可以允许匿名用户和事件目录用户浏览同一个 IIS 7.5 站点吗?

c# - 无需任何 SQL r 数据库服务器即可将动态创建的 datagridview 数据导出到 xml

swift - 是否可以从枚举方法内部更改枚举?

python - 在 python 中将二进制转换为枚举以进行 Redis 转换

c# - 如何使用 BsonClassMap 将 POCO 域对象属性映射为手册或 DBRef 引用?

ios - 尝试使用在 Swift 中具有重复值的枚举

mySQL 根据值提取数字或字符串

c# - 通用方法中的 Linq-to-XML 显式转换

c# - 泛型显式转换