问题描述
有人问我这个问题,在接受采访时:字符串是引用类型或值类型。
I was asked this question in an interview: Is string a reference type or a value type.
我说的引用类型。然后他问我,为什么我们不使用新的运营商在初始化字符串?我说,因为C#语言有一个简单的语法来创建一个字符串,编译器会自动转换code到呼吁System.String类的construcor。
I said its a reference type. Then he asked me why don't we use new operator while initializing the string ? I said because the c# language has a simpler syntax for creating a string and the compiler automatically converts the code into a call for the construcor of the System.String class.
这是答案正确与否?
推荐答案
字符串是不可变的引用类型。还有的 ldstr IL指令,允许推一个新的对象引用字符串。所以,当你写的:
Strings are immutable reference types. There's the ldstr IL instruction which allows pushing a new object reference to a string literal. So when you write:
string a = "abc";
编译器的测试,如果ABC
文字已在元数据中定义,如果没有申报。然后将这种code到以下IL指令:
The compiler tests if the "abc"
literal has already been defined in the metadata and if not declare it. Then it translates this code into the following IL instruction:
ldstr "abc"
这基本上使 A
局部变量指向字符串中的元数据定义。
Which basically makes the a
local variable point to the string literal defined in the metadata.
所以,我要说的是,你的答案是不一样的编译器不把它理解调用构造函数完全正确。
So I would say that your answer is not quite right as the compiler doesn't translate this into a call to a constructor.
这篇关于为什么我们不使用新的运营商在初始化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!