2011-09-16 143 views
1

下面的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) 

回答

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... 
+0

在这里可能应该使用'Enum.TryParse'来处理传入的字符串不是为枚举定义的命名常量之一的情况。 –

+0

@JimL好点。在这些方面,处理任意输入切换语句时,“default”情况通常也是一个好主意。 – LBushkin

相关问题