C# 从枚举中获取整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1963993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the integer value from enum
提问by Anthony
I am working on a basic Battleship gameto help my C# skills. Right now I am having a little trouble with enum. I have:
我正在开发一个基本的战舰游戏来帮助我的 C# 技能。现在我在枚举方面遇到了一些麻烦。我有:
enum game : int
{
a=1,
b=2,
c=3,
}
I would like the player to pass the input "C" and some code return the integer 3
. How would I set it up for it to take a string var (string pick;
) and convert it to the correct int using this enum? The book I am reading on this is bit confusing
我希望玩家传递输入 "C" 并且一些代码返回 integer 3
。我将如何设置它以获取字符串 var ( string pick;
) 并使用此枚举将其转换为正确的 int?我正在阅读的这本书有点令人困惑
采纳答案by R. Martinho Fernandes
Just parse the string and cast to int.
只需解析字符串并转换为 int。
var number = (int)((game) Enum.Parse(typeof(game), pick));
回答by knoopx
just typecasting?
只是类型转换?
int a = (int) game.a
回答by Muad'Dib
// 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;
回答by Jeff
If you're not sure that the incoming string would contain a valid enum value, you can use Enum.TryParse() to try to do the parsing. If it's not valid, this will just return false, instead of throwing an exception.
如果您不确定传入的字符串是否包含有效的枚举值,您可以使用 Enum.TryParse() 尝试进行解析。如果它无效,这将只返回 false,而不是抛出异常。
jp
J.P
回答by mmacneill123
The answer is fine but the syntax is messy.
答案很好,但语法很乱。
Much neater is something like this:
更整洁的是这样的:
public DataSet GetBasketAudit(enmAuditPeriod auditPeriod)
{
int auditParam =Convert.ToInt32(auditPeriod) ;