有时我想为了格式化原因而拆分常量字符串,通常是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#编译器不允许第二种形式成为常量字符串。为什么呢?
答案 0 :(得分:22)
示例代码:
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
) - 并且不允许