C# study notes-summary of string classes

String String class is sealed, modified by sealed, immutable, and string pool.

1. Immutability

   When a string is declared and assigned, the address of the address pointed to by its variable is immutable in the heap. It can be released only when the program ends. Of course, the string can be manipulated through StringBuilder.

//以下操作相当于在堆中开辟五块内存地址
//"a""b""c"在堆中的地址如何没有相应的栈内存指向,会一直保存在堆中,知道程序关闭释放
string a="a";
string b="b";
string c="c";
a=a+b;//结果:ab
a=a+c;//结果abc

2. Character pool 

//s1和s2可以说是两个相同的对象,它们在栈中的地址不一样,但是都指向的是"abc"堆中的地址
//s1和s3不是同一个对象,s3的赋值语句a+b+c相当于在堆中重新开辟了一块内存
string s1="abc";
string s2="abc";
string a="a";
string b="b";
string c="c";
string s3=a+b+c;

   In the process of declaring a string variable and assigning a value, the content of the assignment will be searched in the character pool first, if it exists, the memory address of the variable quality will be directly used, if it does not exist, a new memory address will be opened to store the assigned content 

For dynamic strings that are not in the hash table, this Intern can be added to the hash table for the purpose of improving performance.
(1) StringIntern (xx), the Intern method uses the temporary storage pool to search for a string equal to the value of str. If such a string exists, its reference in the scratch pool is returned. If it does not exist, ask the scratch pool to add a reference to str, and then return the reference.
(2) Sstring Isintemed (xx), this method checks my str in the temporary storage pool. If str has been put into the staging pool, return a reference to this instance; otherwise, return nullNothingnullptrnu reference

3. Why should the sealed keyword be added before the string class?

(1) If the subclass wants to inherit the character string class, it may modify the string class, and the characteristics of the string may change (change the immutability of the string)

(2) The CLR provides various special operation methods for strings. If a large number of subclasses inherit the string class, the CLR needs to provide special operations for more types, which will reduce performance.

4. String formatting

In Console.WriteLine() and string.Format() may need to format the string

Such as string.Format("Today is {0}, I earned {1}", System.DateTime.Now, 800)

Operation on strings: string.Format("Today is {0:D}, I earned {1:C3}", System.DateTime.Now, 800)

{0, 20] means right-aligned and has a width of 20 spaces

{0, -20} means left-aligned, with a width of 20 spaces

{Variable serial number, width: character format}, see Microsoft msdn: compound format for specific operations

 

Guess you like

Origin blog.csdn.net/qq_39157152/article/details/106972424