为什么我不能将常量字符串的串联分配给常量字符串?
有时,出于格式化原因,我想拆分一个常量字符串,通常是 SQL。
const string SELECT_SQL = "SELECT Field1, Field2, Field3 FROM TABLE1 WHERE Field4 = ?";
然而
const string SELECT_SQL = "SELECT Field1, Field2, Field3 "
+ "FROM TABLE1 "
+ "WHERE Field4 = ?";
,C# 编译器不允许第二种形式是常量字符串。为什么?
Occasionally I want to break apart a constant string for formatting reasons, usually SQL.
const string SELECT_SQL = "SELECT Field1, Field2, Field3 FROM TABLE1 WHERE Field4 = ?";
to
const string SELECT_SQL = "SELECT Field1, Field2, Field3 "
+ "FROM TABLE1 "
+ "WHERE Field4 = ?";
However the C# compiler will not allow this second form to be a constant string. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,那应该没问题......你确定它不能编译吗?
示例代码:
我的猜测是,在您的真实代码中,您在串联中包含了一些非常量表达式。
例如,这很好:
但这不是:
这是试图在常量表达式声明中使用非常量表达式 (
MyField
) - 这是不允许的。Um, that should be fine... are you sure it doesn't compile?
Sample code:
My guess is that in your real code you're including some non-constant expression in the concatenation.
For example, this is fine:
but this isn't:
This is attempting to use a non-constant expression (
MyField
) within a constant expression declaration - and that's not permitted.