c# - 连接常量字符串和枚举

标签 c# string enums constants

<分区>

我有一个很大的 C# 类,里面只有 public const string 字段。但是,在一种情况下,我试图将一个字符串和一个枚举值连接到一个 const string 字段中,如下所示:

public const string GET_VALUES = "SELECT * FROM [tbl] WHERE [id] = " + Enum.Val;

但是,我得到了这个编译器错误:

'Namespace.SqlStatements.GET_VALUES' must be constant

我知道我可以删除 const 子句,但我想使此类中的所有字段保持一致。是否可以在 C# 中连接常量字符串和枚举?

最佳答案

来自 MSDN:

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.

在您的情况下,必须使用 ToString 将枚举转换为字符串,这在编译时是不可能的。我建议您将其更改为 readonly,如 elgonzo 所述。

关于c# - 连接常量字符串和枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24953789/

相关文章:

c# - 如何在设计数据库模型中添加 Entity Framework Geolocation 属性

c - 为什么看起来字符串不相等?

java - 如何使用JUNIT测试ENUM

c# - 如何获取avicap32.dll中已连接的网络摄像头列表?

c# - 如何使用 BlobLeaseClient 租用 Azure 存储容器中的单个 blob?

c# - 每个层次结构的表和复合主键

java - 用包含反斜杠 (\) 的字符串替换字符串的最佳方法

java - Java 如何从参数中解析字符串?

c# - 数据表和 AutoGeneratedColummns 中带有枚举的 WPF DataGrid ="True"

c# - 将 Null 转换为 Nullable 枚举(通用)