2011-09-16 145 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

相關問題