开发者

Comparing a string value with the string value of an enum

开发者 https://www.devze.com 2023-04-05 05:31 出处:网络
The C# code below is giving me error on the two lines beginning with case . The error is \"A constant value is expected\"

The C# code below is giving me error on the two lines beginning with case . The error is "A constant value is expected"

The VB.NET code below is working. I'm using this code as a sample for my real app written in C#.

I don't see the problem but that doesn't mean one isn't present. I used a couple of online code converters to double-check the syntax. Both are returning the same result, which gives the error.

ExportFormatType is an enum in a third-party library.

Any suggestions? Thanks!

public void ExportCrystalReport(string exportType, string filePath)
    {
        if (_CReportDoc.IsLoaded == true)
        {
            switch (exportType)
            {
                case  ExportFormatType.PortableDocFormat.ToString():  // Or "PDF"
                    ExportTOFile(filePath, ExportFormatType.Porta开发者_如何转开发bleDocFormat);
                    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)


In C#, case statement labels must be values known at compile time. I don't believe this same restriction holds true for VB.NET.

In principle, ToString() can run arbitrary code, so it's value is not known at compile time (even though in your case it is an enum).

To address this you can either first parse the exportType into a enum, and switch on the enum value in C#:

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

or you could convert the switch to an if/else statement:

if( exportType == ExportFormatType.PortableDocFormat.ToString() )
   // etc...
0

精彩评论

暂无评论...
验证码 换一张
取 消