包含对 Regex.Replace() 和/或 String.Format() 调用的静态字符串声明是否会在编译时得到优化?
根据文章 “如何:连接多个字符串(C# 编程指南)” 字符串文字和字符串常量将在编译时连接成单个字符串。它进一步指出字符串变量只能在运行时连接。
我只有字符串文字和枚举值常量,但我确实有一个稍微复杂的场景,其中它们与两个静态方法调用相结合。为了便于阅读和方便起见,我声明了一个包含 SQL 的静态字符串,如下例所示:
private enum StatGroup
{
Test,
...
}
private static string TestSql =
Regex.Replace(
String.Format(
@"INSERT INTO StatCounts (StatGroup, LinkStatus, LinkCount)
SELECT '{0}', LinkStatus, COUNT(*)
FROM LinkInfo
GROUP BY LinkStatus",
StatGroup.Test),
@"\s+", " ", RegexOptions.Multiline),
我使用 String.Format(),以便我可以利用枚举将有效值插入到 StatGroup
表列中。我使用 Regex 删除 SQL 脚本中不必要的空格。运行时不需要空格,但可以很好地提高代码的可读性。
编译器是否足够聪明,可以在编译时优化上述内容?
According to the article "How to: Concatenate Multiple Strings (C# Programming Guide)" string literals and string constants will be concatentated into a single string at compile time. It further states that string variables can only be concatenated at run time.
I have string literals and enum value constants only, but I do have a slightly more complex scenario where these are combined with two static method calls. For readability and convenience purposes I declare a static string containing SQL as per the below example:
private enum StatGroup
{
Test,
...
}
private static string TestSql =
Regex.Replace(
String.Format(
@"INSERT INTO StatCounts (StatGroup, LinkStatus, LinkCount)
SELECT '{0}', LinkStatus, COUNT(*)
FROM LinkInfo
GROUP BY LinkStatus",
StatGroup.Test),
@"\s+", " ", RegexOptions.Multiline),
I use String.Format(), so that I can utilize the enum for inserting valid value values into the StatGroup
table column. I use Regex to remove the unnecessary whitespace in the SQL script. The whitespace is not required at run time, but serves well for readability of the code.
Is the compiler smart enough to optimize the above at compile time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这些是运行时函数调用。文字的字符串连接对于编译器来说很容易在编译时连接,但 RegEx 和 string.Format 更复杂并且只能在运行时使用。文字的字符串连接是一种特殊情况。
No, those are run-time function calls. String concats of literals are easy for the compiler to join at compile time, but RegEx and string.Format are more complex and are run-time only. String concat of literals is the special case.