将字符串值与枚举的字符串值进行比较

时间:2011-09-16 20:10:19

标签: c# .net-4.0 enums

下面的C#代码给出了以case开头的两行错误。错误是“预期值为常量值”

下面的VB.NET代码正在运行。我正在使用此代码作为我用C#编写的真实应用程序的示例。

我没有看到问题,但这并不意味着没有问题。我使用了几个在线代码转换器来仔细检查语法。两者都返回相同的结果,这会产生错误。

ExportFormatType是第三方库中的枚举。

有什么建议吗?谢谢!

public void ExportCrystalReport(string exportType, string filePath)
    {
        if (_CReportDoc.IsLoaded == true)
        {
            switch (exportType)
            {
                case  ExportFormatType.PortableDocFormat.ToString():  // Or "PDF"
                    ExportTOFile(filePath, ExportFormatType.PortableDocFormat);
                    break;
                case ExportFormatType.CharacterSeparatedValues.ToString(): // Or "CSV"
                    ExportTOFileCSV(filePath, ExportFormatType.CharacterSeparatedValues);

                    break;
            }
        }


 Public Sub ExportCrystalReport(ByVal exportType As String, ByVal filePath As String)

        If _CReportDoc.IsLoaded = True Then
            Select Case exportType
                Case ExportFormatType.PortableDocFormat.ToString 'Or "PDF"
                    ExportTOFile(filePath, ExportFormatType.PortableDocFormat)
                Case ExportFormatType.CharacterSeparatedValues.ToString ' Or "CSV"
                    ExportTOFileCSV(filePath, ExportFormatType.CharacterSeparatedValues)

1 个答案:

答案 0 :(得分:5)

在C#中,case语句标签必须是编译时已知的值。我不认为这同样的限制适用于VB.NET。

原则上,ToString()可以运行任意代码,因此在编译时它的值是未知的(即使在你的情况下它是枚举)。

要解决此问题,您可以先将exportType解析为枚举,然后在C#中打开枚举值:

ExportFormatType exportTypeValue = Enum.Parse(typeof(ExportFormatType), exportType);
switch( exportTypeValue )
{
    case ExportFormatType.PortableDocFormat: // etc...

或者您可以将开关转换为if / else语句:

if( exportType == ExportFormatType.PortableDocFormat.ToString() )
   // etc...
相关问题