c# - 如何比较枚举值和整数值?

标签 c# .net enums

enum MyEnum
{
    Invalid=0,
    Value1=1,
    Value1=2,
}

void main ()
{
    MyEnum e1 = MyEnum.Value1;
    int i1 = 2;

    // Is there any difference how to compare enumEration values with integers?
    if ( e1==(MyEnum)i1 )... // 1st

    if ( (int)e1==i1 )... // 2nd

在上述每种情况下,我们都将枚举转换为 int 或将 int 转换为枚举。

这些转化(性能,任何其他)有什么不同吗?或者它们完全一样?

谢谢。

附言在当前示例中,我将其与“魔数(Magic Number)”进行比较,但在实际应用中,我从数据库的整数字段中获取数据。

最佳答案

这会有所帮助。

var constant = 1;
if(constant == (int)MyEnum.Valid1){
......
}

关于c# - 如何比较枚举值和整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5276100/

相关文章:

c# - 如何在 DotNetNuke 模块中将项目更新发送到数据库?

c# - IIS:处理程序 "aspNetCore"在其模块列表中有一个坏模块 "AspNetCoreModuleV2"

c# - 绑定(bind)一个 [Serializable] 类的 ASP.Net MVC 模型

c# - 有没有混淆C#源代码的程序?

c# - 枚举的显示文本

c# - `stackalloc`关键字的实际使用

c# - SQL 报告服务 : Finding the folder a report is in

.net - .NET 平台文件扩展名是什么?

c# - 一种重构枚举以包含数值的简单方法?

function - 如何在 Elixir 中将 arity 2 的函数作为 Enum.map 的参数传递?