Dieses Snippet zeigt, wie man einen Enum-Wert aus einem String oder int casted.
using System;
namespace ConsoleApp1
{
class Program
{
public enum Car
{
BMW = 1,
Mercedes = 2,
Opel = 3,
Volkswagen = 4,
Ford = 5
}
static void Main(string[] args)
{
// cast from String
string stringToParse = "3";
Car myCarFromString = (Car)Enum.Parse(typeof(Car), stringToParse);
Console.WriteLine("Casted from String: {0}", myCarFromString);
// cast from int
int intToCast = 2;
Car myCarFromInt = (Car)intToCast;
Console.WriteLine("Casted from Int: {0}", myCarFromInt);
Console.Read();
}
}
}
Kommentare zum Snippet