字符串在C#中如何工作? [英] How does string works in c#?

查看:92
本文介绍了字符串在C#中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道字符串是不可变的,一旦创建就无法更改它,我读到如果我们创建一个新的字符串对象并为其分配一个值,然后在内部将另一个值分配给同一字符串对象,实际上创建并分配了新值的另一个对象.假设我有:

I know strings are inmutable, once created we cannot change it, I've read that if we create a new string object and we assign a value to it and then we assign another value to the same string object internally there is actually another object created and assigned with the new value. Let's say I have:

string str = "dog";            
str =  "cat";  

如果我写Console.WriteLine(str);,它将返回cat. 那么内部有两个对象?但是他们有相同的名字吗?它是如何运作的?我已经在Google上进行了一些研究,但还没有找到足够令人信服的信息,因此我可以澄清一下自己的想法. 我知道字符串是引用类型,所以我们在堆栈中有一个对象,该对象具有对堆中某个值的引用,在这种情况下会发生什么情况(请参见上面的代码).

If I write Console.WriteLine(str); it returns cat. So internally there are two objects? But they have the same name? How does it works? I've made some research on google but I have not find yet something convincing enough to me so I can clarify my thoughts about this. I know strings are reference types, so we have an object in the stack with a reference to a value in the heap, what's happening in this case?(see code above).

我上传了一张图片,如果我对堆栈和堆的概念不正确,请向我道歉,这就是为什么我问这个问题. 图片是否反映了代码第一行(string str = "dog";)中发生的情况?然后在第二行代码中会发生什么?堆中的dog值会更改吗?然后在堆栈中创建引用它的新对象?那么,之前存在的对象会发生什么?他们有相同的名字吗? 对于这么多问题我感到抱歉,但我认为这对于正确理解这一点以及了解幕后发生的事情非常重要...

I've upload a picture, apologize me if I'm wrong about the idea of the stack and the heap that's why I'm asking this question. Does the picture reflects what happens in the first line of code(string str = "dog";)? And then what should happen in the second line of code?? The dog value in the heap changes? And then a new object in the stack is created referencing it? Then what happens with the object that was there before? Do they have the same name? I'm sorry for so many questions but I think that is very important to understand this correctly and to know what's happening behind the scenes...

推荐答案

评论字符串实习 .Net String Intern表 CLR实习生池.
基本上,公共语言运行时(CLR)维护一个[唯一]字符串值的表,并且每当您在代码中操作一个字符串时,CLR都会检查该内部表以查看您尝试创建的新值是否已在其中或不.如果是的话,它只是重新分配您要修改的变量以指向内部池中的该条目.如果不是,则将值添加到池中并返回该新引用.池中不再被变量引用的旧值将被垃圾回收.

review String Interning or .Net String Intern table or CLR Intern Pool.
Basically, the Common Language Runtime (CLR) maintains a table of [unique] string values, and whenever you manipulate a string in your code, the CLR examines this intern table to see if the new value you are trying to create is already in there or not. If it is, it just reassigns the variable you are modifying to point to that entry in the intern pool. If not, it adds the value to the pool and returns that new reference. Old values in the pool, no longer referenced by variables, get garbage collected.

这篇关于字符串在C#中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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