且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-05 11:25:46

嗯,那应该没问题...您确定

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.