如果字符串在C#中是不可变的,那我怎么做呢? [英] if strings are immutable in c#, how come I am doing this?

查看:58
本文介绍了如果字符串在C#中是不可变的,那我怎么做呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天读到的是,C#中的字符串是不可变的,就像一旦创建就无法更改,因此下面的代码如何工作

I read today, in c# strings are immutable, like once created they cant be changed, so how come below code works

string str="a";
str +="b";
str +="c";
str +="d";
str +="e";

console.write(str) //output: abcde

变量值如何变化?

推荐答案

使用反射器查看ILM代码,您将确切看到正在发生的事情.尽管您的代码在逻辑上将新内容附加到字符串的末尾,但在后台编译器仍在创建ILM代码,该代码正在为每个分配创建新的字符串.

Use reflector to look at the ILM code and you will see exactly what is going on. Although your code logically appends new contents onto the end of the string, behind the scenes the compiler is creating ILM code that is creating a new string for each assignment.

如果在单个语句中连接文字字符串,则图片会变得更加混乱:

The picture gets a little muddier if you concatenate literal strings in a single statement like this:

str = "a" + "b" + "c" ...

在这种情况下,编译器通常很聪明,不会创建所有多余的字符串(因此适用于垃圾回收器,并将其转换为等效于以下内容的ILM代码:

In this case the compiler is usually smart enough to not create all the extra strings (and thus work for the Garbage collector and will translate it for you to ILM code equivalent to:

str = "abc"

也就是说,像这样在单独的行上执行操作可能不会触发该优化.

That said, doing it on separate lines like that might not trigger that optimization.

这篇关于如果字符串在C#中是不可变的,那我怎么做呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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