C# Study Notes - Data Types

1. Data type

Please add a picture description

1. Data type

1> Type classification

  • Common Type System CTS (Common Type System) is an integral part of the .NET framework, which defines data type rules for all languages ​​oriented to the .NET framework;
  • Value Types: store the data itself
  • Reference type: a reference to store data (memory address)

2> Type attribution

Please add a picture description
insert image description here

2. Memory allocation

1> memory

  • It is a bridge for the CPU to exchange data with other external memories;
  • It is used to store the program and data being executed , that is, the data must be loaded into the memory to be processed by the CPU;
  • Usually the "memory" expressed by developers refers to memory sticks.

2> Allocation

  • When the program is running, the CLR logically divides the requested memory space;
  • Stack area:
    – small space (1MB), fast reading speed
    used to store the method being executed, and the allocated space doubles as a stack frame. Data such as parameters and variables of the method are stored in the stack frame. After the method is executed, the corresponding stack frame will be cleared.
  • Heap area:
    – large space, slow read speed
    used to store reference type data.

3. Local variables

  • Variables defined inside methods
  • Features:
    – There is no default value, you must set the initial value yourself, otherwise it cannot be used
    – When the method is called, it is stored in the stack, and it is cleared from the stack when the method call ends

1> Value type and reference type

  • Value type:
    declared on the stack, data is stored on the stack

  • Reference type:
    declared on the stack, data is stored on the heap, and a reference to the data is stored on the stack

  • Understanding:
    1. Because the method is executed on the stack, the variables declared in the method are all on the stack.
    2. Because the value type directly stores data, the data is stored on the stack.
    3. Because the reference type stores the reference of the data, the data In the heap, the memory address where the data is stored in the stack

2>Garbage collector

  • GC (Garbage Collection) is a service in the CLR that automatically reclaims and releases memory for the managed heap;
  • The GC thread starts tracking from the references in the stack to determine which memory is being used. If the GC cannot track a certain piece of heap memory, it considers that this piece of memory is no longer used and can be reclaimed.

4. Member variables

  • Variables defined outside of methods in a class
  • Features:
    – Has a default value
    – After the class is instantiated, it exists in the heap. When the object is recycled, the member variable is cleared from the heap
    – It can have the same name as the local variable

1> Value type and reference type

  • Value types:
    declared in the heap , data stored in the heap
  • Reference type:
    declared in the heap , and the data is stored in another space of the heap

5. Application

1> compare

		static void Main()
        {
    
    

            int num01 = 1, num02 = 1;
            bool r1 = num01 == num02;//true,因为值类型存储的是数据,所以比较的时数据

            int[] arr01 = new int[] {
    
     1 }, arr02 = new int[] {
    
     1 };
            bool r2 = arr01 == arr02;//false,因为引用类型存储的时数据的引用,所以比较的是存储的引用
            bool r3 = arr01[0]== arr02[0];//ture
        }

2> assignment

		static void Main()
        {
    
    
            // 值类型                                   引用类型
            //int bool char                        string  Array

            //a在栈中   1在栈中
            int a = 1;
            int b = a;
            a = 2;
            Console.WriteLine(b);//?

            //arr在栈中存储数组对象的引用(内存地址)   1在堆中
            int[] arr = new int[] {
    
     1 };
            int[] arr2 = arr;
            //arr2[0] = 2;//修改的是堆中的数据
            arr = new int[]{
    
    2};//修改的是栈中存储的引用
            Console.WriteLine(arr2[0]);//?

            string s1 = "男";
            string s2 = s1;
            s1 = "女";//修改的是栈中存储的引用
            //s1[0]='女';//堆中的文字  不能修改
            Console.WriteLine(s2);//?

            // o1 在栈中   数据1 在堆中
            object o1 = 1;
            object o2 = o1;//o2得到的是数据1 的地址
            o1 = 2;//修改的是栈中o1存储的引用
            Console.WriteLine(o2);//?

        }

Figure 1

Figure II
Figure three
insert image description here

3> pass parameters

		static void Main()
        {
    
    
            int a = 1;
            int[] arr = new int[] {
    
     1 };
            Fun1(a,arr);//实参将 数据1/数组引用  赋值给形参
            Console.WriteLine(a);
            Console.WriteLine(arr[0]);
        }

        private static void Fun1(int a,int[] arr)
        {
    
    
            a = 2;
            //arr[0] = 2;
            arr = new int[] {
    
     2 };
        }

insert image description here
insert image description here
insert image description here

6. Unboxing

1> Packing box

  • The process of implicitly converting a value type to an object type (value type conversion to a reference type) or any interface type implemented by this value type;
  • Internal mechanism:
    1. Open up a memory address in the heap
    2. Copy the data of the value type to the heap
    3. Return the address of the newly allocated object in the heapPlease add a picture description

2> unbox unbox

  • an explicit conversion from an object type to a value type (reference type to value type) or from an interface type to a value type implementing that interface ;
  • Internal mechanism:
    1. Determine whether the given type is the type when boxing
    2. Return the address of the original value type field in the boxed instance

Please add a picture description

        static void Main()
        {
    
    
            int a = 1;
            //int b = a;

            //装箱操作:"比较"消耗性能("最")
            object o = a;

            //拆箱操作:"比较"消耗性能
            int b = (int)o;

			int num = 100;
            string str01 = num.ToString();//没装

            string str02 = "" + num;//装箱
            //string str02 = string.Concat("",num)  //int ==>object

        }
        //形参object类型,实参传递值类型,则装箱
        //可以通过 重载、泛型避免。
  • Note:
    ---- Boxing and unboxing occur: two types must have an inheritance relationship

7、string

  • All data types can be converted to string type by Tostring()

1> Features

  • String constants have the characteristics of a string pool
    1. Before a string constant is created, it first checks whether the same text exists in the string pool. If it exists, it will directly return the object reference; if it does not exist, it will open up space for storage.
    2. Role: Improve memory utilization
  • Strings are immutable
    Once a string constant has memory, it must not change again. Because if it is changed in the original position, the memory of other objects will be destroyed, resulting in a memory leak. When a string variable references a new value, a new string will be created in memory, and the address of the string will be referenced by the variable.
        static void Main()
        {
    
    
            string s1 = "八戒";
            string s2 = "八戒";//同一个字符串

            string s3 = new string(new char[] {
    
     '八', '戒' });//将字符数组转换为字符串
            string s4 = new string(new char[] {
    
     '八', '戒' });

            bool r1 = object.ReferenceEquals(s3, s4);

            //字符串池
            //字符串的不可变性

            //重新开辟空间 存储新字符串,再替换栈中引用
            s1 = "悟空";
            //将文本“八戒”改为“悟空”
            Console.WriteLine(s1);

            //每次修改,都是重新开辟新的空间存储数据,替换栈中引用
            object o1 = 1;
            o1 = 2.0;
            o1 = "ok";
            o1 = true;

            //创建一个计时器,用来记录程序运行的时间
            Stopwatch sw = new StopWatch();
            string strNumber = "";
            for (int i = 0; i < 10; i++)
            {
    
    
                //         ""  + "0"
                //         "0"+ "1"  每次拼接产生新的对象  替换引用 (原有的数据产生1次垃圾)
                strNumber = strNumber + i.ToString();
            }
            sw.Stop();//计时结束
            Console.WriteLine(sw.Elapsed);

            //可变字符串  一次开辟可以容纳10个字符大小的空间
            //优点:可以在原有空间修改字符串,避免产生垃圾
            //适用性:频繁对字符串操作(增加 替换 移除)
            StringBuilder builder = new StringBuilder(10);
            for (int i = 0; i < 10; i++)
            {
    
    
                builder.Append(i);
            }
            builder.Append("是哒");
            string result = builder.ToString();

            builder.Insert(0,"builder");
            //builder.Replace();
            //builder.Remove();

            s1 = s1.Insert(0, "s1");
        }

Please add a picture description

2>Common method

  • ToCharArray (convert a string to a character array)
  • Insert (insert a string at the specified index position)
  • Contains (checks if a character is contained in a string)
  • ToLower (convert all strings to lowercase letters)
  • ToUpper (convert all strings to uppercase letters)
  • IndexOf (returns the index of the first occurrence of a character)-----LastIndexOf (returns the last occurrence of a string)
  • Substring (copy a substring starting from the specified index)
  • Trim (remove blank characters or other predefined characters on both sides of the string)-----TrimEnd, TrimStart (remove the last, remove the first blank or other predefined characters)
  • Split (split the string into an array of strings with certain characters as delimiters)
  • Replace (replace a character in a string)
  • Join (join the strings in the string array, separated by a character)
  • new string(char[] character array name) (can convert character array to string)
  • Length (get the number of characters in the current string)
  • String 1.Equals(String 2, StringComparison.OrdinalIgnoreCase) (ignore case, compare two strings for equality)
  • StartsWith (judging whether the string starts with a substring) -----EndsWith (judging whether the string ends with a substring)
  • Compare (compare two strings)
  • Copy (creates a new instance of String with the same value as the specified String)
  • PadLeft (right-align the characters in this instance, padding on the left with spaces or specified characters to achieve the specified total length) PadRight (left-align, right-padding)
  • The specific implementation of Remove (delete the specified number of characters)
    insert image description here
    insert image description here
    insert image description here
    insert image description here
    can be found in the rookie tutorial: Portal .
		static void Main()
        {
    
    
            string s1 = " sda Hisc as ";
            char[] s2 = s1.ToCharArray(0, 5);
            foreach (var item in s2)
            {
    
    
                Console.WriteLine(item);
            }

            string s3 = s1.Insert(0, "abs");

            bool r1 = s1.Contains('d');

            string s4 = s1.ToLower();

            string s5 = s1.ToUpper();

            int index = s1.IndexOf('i');

            string s6 = s1.Substring(5);

            string s7 = s1.Trim();

            string[] s8 = s1.Split(new char[] {
    
     'a' });

            string s9 = s1.Replace('a', 'b');

            string s10 = string.Join(' ', new string[] {
    
     "dsa", "ewq", "sxc" });
        }
  • Extra method ----ReferenceEquals: Used to compare whether the two have the same reference, it always returns false for the comparison of value type objects; it always returns true for the comparison of two nulls.

3>StringBulid class

  • Unlike the String class, when you modify an instance of the StringBuilder class, you modify the string itself, not a copy of it.
    insert image description here
  • C# String Processing String and StringBuilder: Portal .

8. Enumeration

  • Declare the enumeration under the namespace and outside the class, indicating that all classes under this namespace can use this enumeration
  • We can convert a variable of an enumeration type to an int type and a string type
    . The enumeration type is compatible with the int type by default, so it can be converted through the syntax of mandatory type conversion. When converting a value that is not in an enumeration, no exception will be thrown, but the number will be displayed directly.
    ---- The enumeration can also be converted to and from the string type. If the enumeration type is converted to the string type, call Tostring() directly. If you convert a string to an enumeration type, you need the following line of code:
               ~~~~~~~~~~          (enumeration type to be converted) Enum.Parse(typeof(enumeration type to be converted), "string to be converted");
    if the converted string is a number, even if the enumeration value does not exist, it will not throw exception. If the converted string is text, an exception will be thrown if it is not in the enum.

1> Simple enumeration

  • List all values ​​​​of a certain data
  • Role: enhance the readability of the code, limit the value
  • Syntax: enum name {value1, value2, value3, value4...}
  • The enumeration element is int by default, and the enumeration types are byte, sbyte, short, ushort, int, uint, long or ulong
  • Each enumeration element has an enumeration value. By default, the value of the first enumeration is 0, and the value of each subsequent enumeration is incremented by 1. You can modify the value, and the value of the subsequent enumeration is incremented in turn.

2> Flag enumeration (Flags)

  • When you want to select multiple enumeration values, you can use flag enumeration
  • Specify the [Flags] attribute modifier to indicate that the enumeration can be handled as a bitfield (ie, a set of flags)
  • The result of the | (bit OR) operation of any number of enumeration values ​​cannot be the same as other enumeration values, that is, the value of each flag in the enumeration should be assigned by a power of 2, namely: 1, 2, 4, 8, 16, 32...
namespace Day07
{
    
    
    [Flags] //修饰符
    enum PersonStyle
    {
    
    
        //普通枚举
        //tall=0,                                //0000000000
        //rich=1,                                //0000000001
        //handsome =2,                           //0000000010
        //white =3,                              //0000000011
        //beauty = 4                             //0000000100

        //标志枚举
        tall = 1,                                //0000000001
        rich = 2,                                //0000000010
        handsome = 4,                            //0000000100
        white = 8,                               //0000001000
        beauty = 16                              //0000010000
    }


    /*
     选择多个枚举值
    运算符  |(按位或):两个对应的二进制位中有一个为1,结果位为1
    tall  |  rich  ==>   0000000000 | 0000000001 ==>  0000000001

    条件:
    1.任意多个枚举值做 | 运算 的 结果不能与其他枚举值相同(值以2的N次方递增)
    2.定义枚举时,使用[Flags]特性修饰

    判断标志枚举 是否包含指定枚举值
    运算符  &(按位与):两个对应的二进制位中都为1,结果位为1
    0000000011 & 0000000001  ==> 0000000001    
     */
}

3> bitwise operators

  • Operator | (bitwise OR): one of the two corresponding binary values ​​is 1, and the result bit is 1
    tall | rich ==> 0000000000 | 0000000001 ==> 0000000001
  • Operator & (bitwise AND): Both of the two corresponding binary values ​​are 1, and the result bit is 1
    0000000011 & 0000000001 ==> 0000000001

4> Data type conversion

static void Main(string[] args)
 {
    
    
     //PrintPresonStyle(PersonStyle.tall);
     //00000000001 | 0000010000 ==>  0000010001
     //PrintPresonStyle(PersonStyle.tall | PersonStyle.beauty);

     //数据类型转换
     //int ==> Enum
     PersonStyle style01 = (PersonStyle)2;
     //PrintPresonStyle((PersonStyle)2);

     //Enum ==> int
     int enumNumber =(int) (PersonStyle.beauty | PersonStyle.handsome);

     //string ==> Enum
     //"beauty"

     PersonStyle style02 =(PersonStyle) Enum.Parse(typeof(PersonStyle), "beauty");

     // Enum ==> string
     string strEnum = PersonStyle.handsome.ToString();

 }

private static void PrintPresonStyle(PersonStyle style)
 {
    
    
     if((style & PersonStyle.tall)==PersonStyle.tall)
         Console.WriteLine("大个子");
    else if ((style & PersonStyle.rich)== PersonStyle.rich)
         Console.WriteLine("土豪");
    else if ((style & PersonStyle.handsome) != 0)
         Console.WriteLine("靓仔");
    else if ((style & PersonStyle.white)== PersonStyle.white)
         Console.WriteLine("白净");
    else if ((style & PersonStyle.beauty) != 0)
         Console.WriteLine("美女");
 }

9. Structure

  • Can help us declare multiple variables of different types at once
  • Syntax:
    [public] struct structure name
    {       ~~~~~
         member; //Field
    }
    A variable can only store one value during program execution, while a field can store multiple values. (In order to distinguish it from variables, the fields are generally underlined)

1> What is a structure

  • Definition: A value type used to encapsulate small related variables . Similar to class syntax, both can contain data members and method members. But structs are value types and classes are reference types
  • Applicability:
    Represent lightweight objects such as points and colors, such as creating an array to store 1000 points. If you use a class, you will allocate more memory for each object. Using a structure can save resources

2> Define the structure

Define the structure

  • Defined using the struct keyword
  • Cannot be initialized unless the field is declared const or static
  • Structs cannot be inherited, but interfaces can be implemented
  private static int a = 1;
  private const int b = 1;
  private int rIndex = 0;//报错:结构中不能有实例字段初始化设定项

Constructor

  • Structs always contain parameterless constructors
  • All fields must be initialized in the constructor
struct  Direction
{
    
    
	private int rIndex;
	
	public int RIndex
	{
    
    
	    get
	    {
    
    
	        return this.rIndex;
	    }
	    set
	    {
    
     
	        this.rIndex = value; 
	    }
	}
	
	public int CIndex {
    
     get; set; }
	
	//因为结构体自带无参数构造函数,所以不能包含无参数构造函数
	public Direction()//报错:结构不能包含显式的无参数构造函数
	{
    
    
	}
	
	public Direction (int rIndex,int cIndex):this()//没有:this()好像也没报错,可能是高版本的原因
	{
    
    //构造函数中,必须先为所有字段赋值
	    //:this()  有参数构造函数 先调用无参数构造函数,为自动属性的字段赋值
	    this.rIndex = rIndex;
	    this.CIndex = cIndex;
	}
}

2. Passing by value and passing by reference

  • When value transfer is copied, what is passed is the value itself
  • When the reference type is copied, the reference to the object is passed

Guess you like

Origin blog.csdn.net/Lcl_huolitianji/article/details/119456113