public static readonly string Empty="" VS public const string Empty=""

stop__ 2011-07-16 09:09:30
发现string.cs类中的
Empty定义是这样:
public static readonly string Empty="";

为什么不用
public const string Empty=""
呢?
...全文
240 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
isjoe 2011-07-17
  • 打赏
  • 举报
回复
[Quote=引用楼主 stop__ 的回复:]
发现string.cs类中的
Empty定义是这样:
public static readonly string Empty="";

为什么不用
public const string Empty=""
呢?
[/Quote]

摘自MSDN

readonly 关键字与 const 关键字不同。const 字段只能在该字段的声明中初始化。readonly 字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,readonly 字段可能具有不同的值。另外,const 字段是编译时常数,而 readonly 字段可用于运行时常数


自从用了C#,就一直用readonly。。。以前用VC的时候总用const,太普遍了。
readonly更灵活一些吧
stop__ 2011-07-17
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 caozhy 的回复:]
readonly的好处是,它的变量会被编译到程序里面,运行时只读。
const则编译器直接把它对应的值嵌入程序。

比如
const int i = 3;
...
int a = i; // 等价 int a = 3;

所以如果程序集修改,那么原先的程序const常量会和现在版本的不同。
[/Quote]
这个我想大家都知道吧?
stop__ 2011-07-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 sp1234 的回复:]
注意,我说“.net没有”,不代表语法糖它不好。那是两回事。这里只是说明不同的东西有不同的来龙去脉,而不是相互纠结着的。
[/Quote]

看来.net(CLI)还是有const的。
当然这种问题在实际的工作中是没有任何意义的。
请看:
public static readonly string Empty1 = ""
对应的IL为:
.field public static initonly string Empty1

.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
// Code size 11 (0xb)
.maxstack 8
IL_0000: ldstr ""
IL_0005: stsfld string DevExpressTest.TypeSample::Empty1
IL_000a: ret
} // end of method TypeSample::.cctor


public const string Empty2 = "";

对应的IL为:
.field public static literal string Empty2 = ""

不过在codeproject看到一篇文章分析好像是对性能有影响.
  • 打赏
  • 举报
回复
注意,我说“.net没有”,不代表语法糖它不好。那是两回事。这里只是说明不同的东西有不同的来龙去脉,而不是相互纠结着的。
  • 打赏
  • 举报
回复
是的!

你可以这样理解:.net根本没有const这种东西,这是c#编译器的语法糖。.net只有static readonly。
threenewbee 2011-07-16
  • 打赏
  • 举报
回复
readonly的好处是,它的变量会被编译到程序里面,运行时只读。
const则编译器直接把它对应的值嵌入程序。

比如
const int i = 3;
...
int a = i; // 等价 int a = 3;

所以如果程序集修改,那么原先的程序const常量会和现在版本的不同。

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧