C# 如何从字符串变量创建常量字符串

C# 如何从字符串变量创建常量字符串,c#,string,constants,C#,String,Constants,我想从另一个字符串变量创建常量字符串。例如,接下来的两个代码段无法编译 (一) (二) 导致 Error: The expression being assigned to 'str2' must be constant 有没有办法从字符串变量创建常量字符串?简而言之-没有 分配给常量的值必须是编译时常量 您可以使用readonly而不是const,这将允许您更改变量的值-您将只能更改构造函数中的引用。使用readonly关键字 没有。因为const变量是在编译时工作的 每个人都同意使用只读

我想从另一个字符串变量创建常量字符串。例如,接下来的两个代码段无法编译

(一)

(二)

导致

Error: The expression being assigned to 'str2' must be constant 
有没有办法从字符串变量创建常量字符串?

简而言之-没有

分配给
常量的值必须是编译时常量

您可以使用
readonly
而不是
const
,这将允许您更改变量的值-您将只能更改构造函数中的引用。

使用readonly关键字


没有。因为
const
变量是在编译时工作的

每个人都同意使用
只读

readonly string t = s + " World";

常量是在编译时计算的,所以不可能实现您想要的。但是,您可以将常量替换为只读,例如:

string s = "Hello";
readonly string t = s + " World";

常量变量在编译过程中必须是完全已知的,因此这是不可能的。在这些情况下,使用readonly关键字代替Constant
static readonly
可以帮助替换。
string str = "111";
readonly string str2 = str.ToCharArray();
readonly string t = s + " World";
string s = "Hello";
readonly string t = s + " World";