[英]What is the difference between the two definitions?
string a = "var";
string b = new string("var");
I also have an extra question, How do I access the string type variable in the 1st definition without allocating space in the heap?我还有一个额外的问题,如何在不分配堆空间的情况下访问第一个定义中的字符串类型变量?
The first one compiles;第一个编译; the second one doesn't, producing a CS1503 error:
第二个没有,产生 CS1503 错误:
Argument 1: cannot convert from 'string' to 'char*'
参数 1:无法从 'string' 转换为 'char*'
That is because the String
class does not have a constructor which accepts a string
parameter.这是因为
String
class 没有接受string
参数的构造函数。
The first one assigns the literal to a string variable.第一个将文字分配给字符串变量。 The second one implicitly casts the string to a
ReadOnlySpan<char>
, then calls the String
constructor which accepts a ReadOnlySpan<char>
instance, which copies the characters from the original string to a new string, doubling the memory usage.第二个将字符串隐式转换为
ReadOnlySpan<char>
,然后调用接受ReadOnlySpan<char>
实例的String
构造函数,该实例将字符从原始字符串复制到新字符串,从而使 memory 的使用加倍。
As to your second question, since the String
is a reference type, you cannot allocate an instance without allocating space in the heap.至于您的第二个问题,由于
String
是一种引用类型,因此您不能在不分配堆空间的情况下分配实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.