为什么我不能将常量字符串的串联分配给常量字符串?

有时我想分解一个常量字符串,原因是格式化,通常是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#编译器不允许第二种forms为常量字符串。 为什么?

嗯,那应该没事……你确定它不会编译吗?

示例代码:

 using System; class Test { const string MyConstant = "Foo" + "Bar" + "Baz"; static void Main() { Console.WriteLine(MyConstant); } } 

我的猜测是,在你的真实代码中,你在连接中包含了一些非常量表达式。

例如,这很好:

 const string MyField = "Field"; const string Sql = "SELECT " + MyField + " FROM TABLE"; 

但这不是:

 static readonly string MyField = "Field"; const string Sql = "SELECT " + MyField + " FROM TABLE"; 

这是试图在常量表达式声明中使用非常量表达式( MyField ) – 这是不允许的。