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

发布于 2024-10-19 00:25:09 字数 372 浏览 1 评论 0原文

有时,出于格式化原因,我想拆分一个常量字符串,通常是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_失温 2024-10-26 00:25:09

嗯,那应该没问题......你确定它不能编译吗?

示例代码:

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) - 这是不允许的。

Um, that should be fine... are you sure it doesn't compile?

Sample code:

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.

For example, this is fine:

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

but this isn't:

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

This is attempting to use a non-constant expression (MyField) within a constant expression declaration - and that's not permitted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文