C# 将枚举类型值与int进行比较

C# 将枚举类型值与int进行比较,c#,enums,C#,Enums,我正在开发一个C#应用程序,我有以下枚举: public enum TourismItemType : int { Destination = 1, PointOfInterest = 2, Content = 3 } 我还有一个int变量,我想检查该变量是否等于TourismItemType.Destination,如下所示: int tourismType; if (int.TryParse(NavigationContext.QueryString.Valu

我正在开发一个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;
    }
}
但它抛出了一个错误

我该怎么做


谢谢。

tourismType
转换为您的枚举类型,因为没有从int进行隐式转换

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

您可以使用将tourismType解析为您的枚举类型,也可以将枚举值视为int,如:
case(int)tourismType.Destination。
试试看

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

当然,您也可以在交换机的
默认值:
情况下处理无效的tourismType。

如果您正在运行.NET 4,则可以使用以下方法:


我知道你现在有答案了,但总的来说,把抛出的错误的细节放进去,而不仅仅是说有一个。即使这个错误对你来说毫无意义,它也可能对其他人有意义。
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
}
TourismItemType tourismType;
if (Enum.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    switch (tourismType)
    {
        case TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}