This article mainly introduces the general and specific knowledge of string in C#, which has a very good reference value. Let’s take a look at it with the editor. Bar
The string type is one of the primitive types of C#. It is a reference type, corresponding to the System.String type in FCL. What are the similarities and differences between the string type and ordinary reference types?
#1. Strings have fixed invariance. Strings exist under the System.String namespace. Through the decompilation tool, we can see:
There are only two read-only properties in the string, and there are no settable properties, so instances of the string type have fixed transsexual. As long as the content of the string is changed, the system will generate a brand new string in the heap memory. In fact, this cannot be regarded as a special characteristic of strings. It is no different from ordinary reference types. It is just that when the string type is defined, no writable attributes are created, so this can only be regarded as a general characteristic of strings. .
The demo code is as follows:
class Program { static void Main(string[] args) { string str1 = "Hi"; string str2 = str1; str2 = "Hello"; //这个操作相当于给实例str2重新new了一个实例 Console.WriteLine("str1的值为:{0}", str1); Console.WriteLine("str2的值为:{0}", str2); Console.ReadKey(); } }
The running results are as follows:
2. The concept of the resident pool in strings, This is specific to the string type, so this is a peculiarity of strings. When the string we declare has the same value as a string that already exists in the heap, space will not be opened up in the heap and a new instance will be created. Instead, the reference of the currently declared string will point to the existing instance.
The above is the detailed content of A detailed introduction to the generality and particularity of strings in C# (pictures and text). For more information, please follow other related articles on the PHP Chinese website!