I'm developing a C# application and I have the following enum:
public enum TourismItemType : int
{
Destination = 1,
PointOfInterest = 2,
Content = 3
}
And I also have a int variable, and I want to check that variable to know it is equal to TourismItemType.Destination
, like this:
int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
switch (tourismType)
{
case TourismItemType.Destination:
ShowDestinationInfo();
break;
case TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
But it throws an error.
How can I do that?
Thanks.
Cast tourismType
to your enum type as there is no implicit conversion from ints.
switch ((TourismItemType)tourismType)
//...
If you're running .NET 4 then you can use the Enum.TryParse
method:
TourismItemType tourismType;
if (Enum.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
switch (tourismType)
{
case TourismItemType.Destination:
ShowDestinationInfo();
break;
case TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
您可以使用Enum.TryParse将tourismType解析为您的枚举类型,或者您可以将枚举值视为int,如: case (int)TourismType.Destination.
Try
int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
switch (tourismType)
{
case (int)TourismItemType.Destination:
ShowDestinationInfo();
break;
case (int)TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
or
int tourismType;
TourismItemType tourismTypeEnum;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
tourismTypeEnum = (TourismItemType)tourismType;
switch (tourismTypeEnum)
{
case TourismItemType.Destination:
ShowDestinationInfo();
break;
case TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
You could also do:
int tourismType;
if ( int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType )
{
if ( Enum.IsDefined(typeof(TourismItemType), tourismType) )
{
switch ((TourismItemType)tourismType)
{
...
}
}
else
{
// tourismType not a valid TourismItemType
}
}
else
{
// NavigationContext.QueryString.Values.First() not a valid int
}
Of course you could also handle invalid tourismType in the switch's default:
case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.