Getting the integer value from enum


Question


I am working on a basic Battleship game to help my C# skills. Right now I am having a little trouble with enum. I have:

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


Answer 1:


Just parse the string and cast to int.

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



Answer 2:


// 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; 



Answer 3:


just typecasting?

int a = (int) game.a



Answer 4:


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.

jp




Answer 5:


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) ;


来源:https://stackoverflow.com/questions/1963993/getting-the-integer-value-from-enum


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。
2、本站所有主题由该帖子作者发表,该帖子作者一念成空码神部落享有帖子相关版权。
3、码神部落管理员和版主有权不事先通知发贴者而删除本文。
4、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者一念成空码神部落的同意。
5、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任。
6、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责。
7、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。

最新回复 (0)
    • 码神部落
      2
        立即登录 立即注册 GitHub登录
返回
发新帖
作者最近主题: