从枚举中获取整数值

问题描述:

我正在使用基本的Battleship game来帮助我的C#技能。现在我在枚举中遇到了一些麻烦。我有:从枚举中获取整数值

enum game : int 
{ 
    a=1, 
    b=2, 
    c=3, 
} 

我想玩家通过输入“C”和一些代码返回整3。我如何设置它为它采取一个字符串变种(string pick;)并使用此枚举将其转换为正确的int?我在读这本书是有点混淆

+2

这是不好的做法,用枚举比'int'其他和'int'是默认的,所以你不需要让它明确的底层类型。只是说。 – 2009-12-26 18:38:37

+2

不是你的问题“从字符串中获取枚举值”? – knoopx 2009-12-26 18:40:52

只解析字符串并转换为int。

var number = (int)((game) Enum.Parse(typeof(game), pick)); 
+0

非常感谢 – Anthony 2009-12-26 18:42:57

+0

我看到了类似的效果(int)(游戏)选择表达式 – 2012-08-25 17:29:03

+1

什么是“挑”在这里? – gdmanandamohon 2017-07-21 10:52:37

只是类型转换?

int a = (int) game.a 
+0

不 - 这不是OP要找的。 – Jeff 2010-11-28 14:50:24

+0

正是我需要的,谢谢! – Jamie 2017-03-16 14:45:31

// convert string to enum, invalid cast will throw an exception 
game myenum =(game) Enum.Parse(typeof(game), mystring); 

// convert an enum to an int 
int val = (int) myenum; 

// convert an enum to an int 
int n = (int) game.a; 

如果你不知道传入的字符串将包含一个有效的枚举值,你可以使用Enum.TryParse()尝试做解析。如果它无效,这只会返回false,而不是抛出异常。

jp

答案很好,但语法很混乱。

更整洁是这样的:

public DataSet GetBasketAudit(enmAuditPeriod auditPeriod) 
    { 
     int auditParam =Convert.ToInt32(auditPeriod) ;