如何在C#中将int转换为枚举?
当前回答
我正在使用这段代码将int转换为枚举:
if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }
我觉得这是最好的解决方案。
其他回答
有时您有一个MyEnum类型的对象。喜欢
var MyEnumType = typeof(MyEnum);
然后:
Enum.ToObject(typeof(MyEnum), 3)
对于数值,这是更安全的,因为无论发生什么情况,它都会返回一个对象:
public static class EnumEx
{
static public bool TryConvert<T>(int value, out T result)
{
result = default(T);
bool success = Enum.IsDefined(typeof(T), value);
if (success)
{
result = (T)Enum.ToObject(typeof(T), value);
}
return success;
}
}
我正在使用这段代码将int转换为枚举:
if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }
我觉得这是最好的解决方案。
如果您有一个用作位掩码的整数,并且可以表示[Flags]枚举中的一个或多个值,则可以使用此代码将各个标志值解析为列表:
for (var flagIterator = 0; flagIterator < 32; flagIterator++)
{
// Determine the bit value (1,2,4,...,Int32.MinValue)
int bitValue = 1 << flagIterator;
// Check to see if the current flag exists in the bit mask
if ((intValue & bitValue) != 0)
{
// If the current flag exists in the enumeration, then we can add that value to the list
// if the enumeration has that flag defined
if (Enum.IsDefined(typeof(MyEnum), bitValue))
Console.WriteLine((MyEnum)bitValue);
}
}
注意,这假设枚举的基础类型是有符号的32位整数。如果是不同的数字类型,则必须更改硬编码32以反映该类型中的位(或使用Enum.GetUnderlyingType()以编程方式导出)
从int:
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);
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 使用Enum实现单例(Java)