具有基础类型的枚举。无意中返回字符串表示

时间:2014-01-09 12:16:49

标签: c# enums

我有以下枚举:

 public enum BikeType : byte
  {
    Road = 0,
    Mountain = 1
  };

当我尝试将其传递给I时,检索字节的'字符串'表示,而不是数值:

string str = string.Format("Road bike has a byte value of {0}", BikeType.Road);

"Road bike has a byte value of Road"

我想要字节值(0)。我做错了什么?

由于

2 个答案:

答案 0 :(得分:6)

你需要进行转换为int

string str = 
          string.Format("Road bike has a byte value of {0}", (int)BikeType.Road);

如果您不投弃它,它会在ToString上致电BikeType.RoadRoad将返回{{1}}

答案 1 :(得分:2)

你应该转为byte

string str = string.Format("Road bike has a byte value of {0}", (byte)BikeType.Road);