未定义时枚举不默认为 0
Enum not default to 0 when not defined
我有一个枚举类型定义如下:
public enum OperationTypeEnum : byte
{
/// <remarks/>
@__NONE = 0,
/// <remarks/>
Sale = 1,
/// <remarks/>
Auth = 2
}
在我的代码中,我像这样投射了一个整数:
var operationType = (OperationTypeEnum) anotherIntVariable;
当 anotherIntVariable 未定义(例如 5)时,我希望返回 0 或 __NONE(因为 5 未定义为有效枚举值之一,但我收到的是 5。
我需要更改什么才能使未定义的枚举值变为 0?
谢谢!
C# 枚举实际上是整数,并且没有编译或 运行 时间检查您是否正在使用定义的枚举集中的 "valid" 值。有关详细信息,请参阅此答案
如果获取的是数值,只需要获取实际的枚举值,可以使用Enum.TryParse
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.
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);
}
}
}
最安全的方法是为您的枚举创建一个扩展方法 class,它将比较枚举值,如果 none 个初始化为 @__NONE
如果您确定只有有限数量的枚举值:
public static class OperationTypeEnumExtensions
{
public static OperationTypeEnum ToOperationTypeEnum(this int val)
{
switch (val)
{
case (int) OperatinTypeEnum.Sale:
return OperationTypeEnum.Sale;
cast (int) OperationTypeEnum.Auth:
return OperationTypeenum.Auth;
default:
return OperationTypeEnum.@_none;
}
}
}
用法:
int myInt = GetMyIntValue();
OperationTypeEnum myEnum = myInt.ToOperationTypeEnum();
@plast1k 给出了答案
这是针对您的问题的通用扩展
public static class OperationTypeEnumExtensions
{
public static T ToEnum<T>(this byte val) where T : struct
{
if(Enum.IsDefined(typeof(T), val))
return (T) Enum.Parse(typeof(T), val.ToString());
return default(T);
}
}
用法
value.ToEnum<OperationTypeEnum>()
#如果你的枚举class定义如下。
public enum CategoryEnum : int
{
Undefined = 0,
IT= 1,
HR= 2,
Sales= 3,
Finance=4
}
现在如果你想在值不匹配 1,2,3,4 的情况下找到未定义的枚举,那么使用下面的 Enum.IsDefine() 函数
Enum.IsDefined(typeof(CategoryEnum), request.CategoryId)
#returns true if id matches any enum values
#else returns false
现在将枚举值解析为字符串
public enum Mode
{
UNDEFINED = 0,
APP = 1,
TEXT = 2,
}
var value = Enum.TryParse(request.Mode, true, out Mode mode);
#returns mode enum
#现在获取id或vice-vera对应的值,有如下扩展方法:
public static T AsEnum<T>(this string input) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
Enum.TryParse(input, ignoreCase: true, out T result);
return (T)result;
}
- 然后使用 AsEnum() 函数获取它:
var status = searchText.AsEnum<StatusEnum>();
我有一个枚举类型定义如下:
public enum OperationTypeEnum : byte
{
/// <remarks/>
@__NONE = 0,
/// <remarks/>
Sale = 1,
/// <remarks/>
Auth = 2
}
在我的代码中,我像这样投射了一个整数:
var operationType = (OperationTypeEnum) anotherIntVariable;
当 anotherIntVariable 未定义(例如 5)时,我希望返回 0 或 __NONE(因为 5 未定义为有效枚举值之一,但我收到的是 5。
我需要更改什么才能使未定义的枚举值变为 0?
谢谢!
C# 枚举实际上是整数,并且没有编译或 运行 时间检查您是否正在使用定义的枚举集中的 "valid" 值。有关详细信息,请参阅此答案
如果获取的是数值,只需要获取实际的枚举值,可以使用Enum.TryParse
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.
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);
}
}
}
最安全的方法是为您的枚举创建一个扩展方法 class,它将比较枚举值,如果 none 个初始化为 @__NONE
如果您确定只有有限数量的枚举值:
public static class OperationTypeEnumExtensions
{
public static OperationTypeEnum ToOperationTypeEnum(this int val)
{
switch (val)
{
case (int) OperatinTypeEnum.Sale:
return OperationTypeEnum.Sale;
cast (int) OperationTypeEnum.Auth:
return OperationTypeenum.Auth;
default:
return OperationTypeEnum.@_none;
}
}
}
用法:
int myInt = GetMyIntValue();
OperationTypeEnum myEnum = myInt.ToOperationTypeEnum();
@plast1k 给出了答案
这是针对您的问题的通用扩展
public static class OperationTypeEnumExtensions
{
public static T ToEnum<T>(this byte val) where T : struct
{
if(Enum.IsDefined(typeof(T), val))
return (T) Enum.Parse(typeof(T), val.ToString());
return default(T);
}
}
用法
value.ToEnum<OperationTypeEnum>()
#如果你的枚举class定义如下。
public enum CategoryEnum : int
{
Undefined = 0,
IT= 1,
HR= 2,
Sales= 3,
Finance=4
}
现在如果你想在值不匹配 1,2,3,4 的情况下找到未定义的枚举,那么使用下面的 Enum.IsDefine() 函数
Enum.IsDefined(typeof(CategoryEnum), request.CategoryId)
#returns true if id matches any enum values
#else returns false
现在将枚举值解析为字符串
public enum Mode
{
UNDEFINED = 0,
APP = 1,
TEXT = 2,
}
var value = Enum.TryParse(request.Mode, true, out Mode mode);
#returns mode enum
#现在获取id或vice-vera对应的值,有如下扩展方法:
public static T AsEnum<T>(this string input) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
Enum.TryParse(input, ignoreCase: true, out T result);
return (T)result;
}
- 然后使用 AsEnum() 函数获取它:
var status = searchText.AsEnum<StatusEnum>();