为什么不能将常量字符串的串联分配给常量字符串? [英] Why can I not assign the concatenation of constant strings to a constant string?
本文介绍了为什么不能将常量字符串的串联分配给常量字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时出于格式原因,我想将常量字符串拆开,通常是SQL。
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 = ?";
至
const string SELECT_SQL = "SELECT Field1, Field2, Field3 "
+ "FROM TABLE1 "
+ "WHERE Field4 = ?";
但是C#编译器不允许第二种形式为常量字符串。为什么?
However the C# compiler will not allow this second form to be a constant string. Why?
推荐答案
嗯,那应该没问题...您确定
Um, that should be fine... are you sure it doesn't compile?
示例代码:
using System;
class Test
{
const string MyConstant = "Foo" + "Bar" + "Baz";
static void Main()
{
Console.WriteLine(MyConstant);
}
}
我的猜测是您的真实代码中,您要在串联中包含一些非常数表达式。
My guess is that in your real code you're including some non-constant expression in the concatenation.
例如,这很好:
const string MyField = "Field";
const string Sql = "SELECT " + MyField + " FROM TABLE";
但这不是:
static readonly string MyField = "Field";
const string Sql = "SELECT " + MyField + " FROM TABLE";
这是尝试使用非常量表达式( MyField
)包含在常量表达式声明中-不允许 。
This is attempting to use a non-constant expression (MyField
) within a constant expression declaration - and that's not permitted.
这篇关于为什么不能将常量字符串的串联分配给常量字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文