【问题标题】:why enum needs to cast to int while comparing with integer value in C#为什么枚举在与 C# 中的整数值进行比较时需要强制转换为 int
【发布时间】:2018-01-09 05:23:09
【问题描述】:

例如,我在 C# 中声明了以下enum

C#代码:

public enum LobMaster :int 
{
    RetailBroking = 1,
    HNI = 2,
    TechnologyInfrastructure = 3,
}

cshtml代码:

@int code = 2
@if (LobMaster.RetailBroking == code)
{

}

如果我尝试将 int 枚举与整数值进行比较,它会给我以下错误消息。

运算符 '==' 不能应用于类型 'LobMaster' 和 'int'

虽然我的枚举

LobMaster

已经是 int 类型了。

但是当我将枚举转换为 int 然后与 int 值进行比较时,它可以正常工作。 所以我的问题是为什么我需要将枚举转换为 int,因为枚举已经是一个 int。

【问题讨论】:

  • “虽然我的枚举已经是 int 类型” - 不正确。这不是 c/c++
  • enum 不是int,只是它的底层类型是int
  • 来自documentation - 底层类型指定为每个枚举器分配多少存储空间。但是,从枚举类型转换为整数类型需要显式转换

标签: c# asp.net asp.net-mvc enums


【解决方案1】:

Enums 的主要目的是去除“幻数”,所以你应该问问自己——为什么要使用那些幻数?

更好的比较是:

Session["Lob_code"] is LobMaster && LobMaster.MassAffluent == (LobMaster)Session["Lob_code"]

这样你就可以避免那些神奇的数字,你的代码只提供所有的上下文。

【讨论】:

    【解决方案2】:
    @if ((int) LobMaster.MassAffluent == Convert.ToInt32(Session["Lob_code"])) { }
    

    你应该能够投射左手值,然后做 conoarison

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多