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