string是值类型,但为什么有的地方表现出的是引用类型的特征呢?

YiYanXiYin 2005-04-30 05:27:28
有个问题一直没搞清楚
string是值类型,但为什么有的地方表现出的是引用类型的特征呢?
我举个例子
using System;

class Program
{
static void Main(string[] args)
{
int i = 10;
string s = "abc";
object o = i;
o = s;
}
}
这段代码就能说明问题
i是值类型,这个毋庸置疑,i赋给o肯定要box一次,值类型的特性
按理说s赋给o也要box一次,也是值类型的特性
但是,请看下面的il代码
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 19 (0x13)
.maxstack 1
.locals init ([0] int32 i,
[1] string s,
[2] object o)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldstr "abc"
IL_0008: stloc.1
IL_0009: ldloc.0
IL_000a: box [mscorlib]System.Int32
IL_000f: stloc.2
IL_0010: ldloc.1
IL_0011: stloc.2
IL_0012: ret
} // end of method Program::Main
i已经box了,这是对的,但是s却没有,为什么?迷惑呀
...全文
133 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
YiYanXiYin 2005-04-30
  • 打赏
  • 举报
回复
简直昏s,糊涂了,糊涂了
Jim3 2005-04-30
  • 打赏
  • 举报
回复
string 是引用类型

他和别的引用类型不同,il不用newobj来创建他

而是用ldstr

可以查“字符串驻留”(string interning)
lucbesson 2005-04-30
  • 打赏
  • 举报
回复
string和类
lucbesson 2005-04-30
  • 打赏
  • 举报
回复
string 类 是应用类型,不是值类型 。
yingchenglangzi 2005-04-30
  • 打赏
  • 举报
回复
string是所有基本类型中唯一的引用类型而不是值类型
Eddie005 2005-04-30
  • 打赏
  • 举报
回复
是引用类型

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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