将enumType值与int进行比较

时间:2010-07-29 10:53:56

标签: c# enums

我正在开发一个C#应用程序,我有以下枚举:

public enum TourismItemType : int
{
     Destination = 1,
     PointOfInterest = 2,
     Content = 3
}

我还有一个int变量,我想检查那个变量,知道它等于TourismItemType.Destination,如下所示:

int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    switch (tourismType)
    {
        case TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}

但它会引发错误。

我该怎么做?

感谢。

5 个答案:

答案 0 :(得分:5)

tourismType投射到您的枚举类型,因为没有来自整数的隐式转换。

switch ((TourismItemType)tourismType)
//...

答案 1 :(得分:2)

如果您运行的是.NET 4,则可以使用Enum.TryParse方法:

TourismItemType tourismType;
if (Enum.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    switch (tourismType)
    {
        case TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}

答案 2 :(得分:1)

您可以使用Enum.TryParse将tourismType解析为枚举类型,或者您可以将枚举值视为int,如:case (int)TourismType.Destination.

答案 3 :(得分:1)

尝试

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

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

答案 4 :(得分:1)

你也可以这样做:

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
}

当然,你也可以在交换机的default:案例中处理无效的tourismType。

相关问题