孟清妍 发表于 2025-5-29 20:20:28

关于System.String的几个认识

1.String分配了之后就无法更改?
下面的代码会造成编译错误:
 
        string s = "hello";
        s='a'; 
会造成:
Error 3 Property or indexer 'string.this' cannot be assigned to -- it is read only 
事实上是可以改变的:
 
        unsafe
        {
            string s = "hello";
            fixed (char* p1 = s)
            {
                *p1='a';
            }
        } 
 
2.String不能用new来构造?
由于代码
 
string s=new string("hello"); 
会报错,没有此类ctor但是实际上string有8个ctor:
 
public String(char* value);
public String(char[] value);
public String(sbyte* value);
public String(char c, int count);
public String(char* value, int startIndex, int length);
public String(char[] value, int startIndex, int length);
public String(sbyte* value, int startIndex, int length);
public String(sbyte* value, int startIndex, int length, Encoding enc); 
 
3.字符串“+”会生成新的字符串?
 
string s="he"+"ll"+"o"; 
看看IL:
 
  IL_0000:  nop
  IL_0001:  ldstr      "hello"
  IL_0006:  stloc.0
  IL_0007:  ret
 
事实上是一个字符串,编译器做了我们不知道的事情。
 
4.StringBuilder为什么会比String性能好?
 
String s = null;
for (int i = 0; i 
页: [1]
查看完整版本: 关于System.String的几个认识