首页 新闻 会员 周边

String.Empty

0
[待解决问题]

为什么String.Empty是设计成static readonly而不是const?

轶寒的主页 轶寒 | 初学一级 | 园豆:4
提问于:2021-08-31 22:41
< >
分享
所有回答(1)
1

const 表示常量. 编译时就确定了 例如

const string a="";
void method(){
string b=a;
};

编译后的代码实际是==>

void method(){
string b="";
};

readonly 是运行时'常量', 这里的常量我打引号了哈.
static readonly a=""; ==> 可以理解为 是static readonly a=new string(""); 这里的"" 实际上是 '\0'. 0长度&null结尾的字符串.

static readonly a=new string(""); 
void method(){
string b=a;
};

==>编译后

static readonly a=new string(""); 
void method(){
string b=a;
};
czd890 | 园豆:14412 (专家六级) | 2021-09-01 11:42

大佬对``const``和``static readonly``的解释已经很清楚了,至于说为什么不用``const``,其实也不是不能用了,别较真,如果用了``const``你又会问为什么不用``static readonly``

支持(0) 反对(0) 龙葛格 | 园豆:782 (小虾三级) | 2021-09-01 15:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册