问题
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
回答1:
Just parse the string and cast to int.
var number = (int)((game) Enum.Parse(typeof(game), pick));
回答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;
回答3:
just typecasting?
int a = (int) game.a
回答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
回答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