C#中的“常量字符串”与“静态只读字符串” [英] 'const string' vs. 'static readonly string' in C#

查看:179
本文介绍了C#中的“常量字符串”与“静态只读字符串”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,

static readonly string MyStr;

const string MyStr;

推荐答案

使用 const 字符串时,编译器会在编译时嵌入字符串的值

因此,如果您在其他程序集中使用 const 值,然后更新原始程序集并更改值,其他程序集将不会看到更改,直到您重新 compile

When you use a const string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.

静态只读字符串是在运行时会查询的普通字段。因此,如果在不同的程序集中更改了字段的值,则在程序集加载后即会看到更改,而无需重新编译。

A static readonly string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.

这也意味着静态只读字符串可以使用非恒定成员,例如 Environment.UserName DateTime。现在.ToString() const 字符串只能使用其他常量或文字进行初始化。

此外,静态只读可以在静态构造函数中设置字符串; const 字符串只能内联初始化。

This also means that a static readonly string can use non-constant members, such as Environment.UserName or DateTime.Now.ToString(). A const string can only be initialized using other constants or literals.
Also, a static readonly string can be set in a static constructor; a const string can only be initialized inline.

请注意,静态字符串可以修改;您应该改用静态只读

Note that a static string can be modified; you should use static readonly instead.

这篇关于C#中的“常量字符串”与“静态只读字符串”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆