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

标签 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)

最佳答案

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

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

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

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

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

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

关于c# - 将字符串值与枚举的字符串值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449883/

相关文章:

java - 在类外部声明的枚举

java - 在接口(interface)中声明枚举时出错

c# - 将 PDF 流式传输到网页失败

c# - 将 linq to sql 结果放入层次结构中,以便在无序列表中使用(对于 jquery 树)

c# - 从 ASP 路由处理程序返回 PHP 页面

c# - 如何在不强制转换的情况下从自己的类调用扩展方法?

java - 实现类似的缺失一项特征

c# - 设置属性 'System.Windows.FrameworkElement.Height' 抛出异常

c# - 如何从中继器获取更新的文本框值?

wcf - 通过.NET 1.1调用.NET 4.0组件