C#--- Liu tiemanganese introduction to c# language learning note 07 (p10p11p12) (operator, essence of operator, expression)

1. Operator overview, operator essence and operator priority

Essence: operators, expressions and statements serve methods. Operators and operands form expressions, and expressions plus semicolons form statements;

Statements are used to form the method body (method and algorithm logic)

The essence of operators is functions (increased readability)

An operator cannot be separated from its associated data type (an operator is a shorthand for a set of basic algorithms associated with a fixed type)

(each data type has operations related to it)

Priority: you can increase the priority by adding parentheses. Parentheses can be nested. Calculate the innermost expression first

The priority operator at the same level, when there is no assignment function, has assignment function from left to right, and has assignment function from right to left

There is no combination law for operations with the same priority

Judging by priority and from left to right (or from right to left), it is judged that there is only one way, and there are no multiple ways.

Operator: not all methods need to use method call operators.

Delegate: a type that does not directly call a method, but indirectly calls a method through a delegate

//entrust
 static void Main(string[] args)
        {
            Calculator c = new Calculator();
            Action myAction = new Action(c.PrintHello);//This delegate can be used for methods whose return value type is void and the parameter is empty
            //Give PrintHello to myAction for management instead of calling directly, and hand in the member name
            myAction();//Call through myaction
        }
    }

    class Calculator
    {
        public double Add(double a,double b)
        {
            return a + b;
        }

        public void PrintHello()
        {
            Console.WriteLine("hello");
        }
    }

[] access the elements, arrays, dictionaries and index of the set. The indexes are not necessarily integers

When accessing an array, the index is an integer, but when accessing a dictionary, the index is not necessarily an integer

A generic class itself is not necessarily a complete class. It must be combined with other classes to form a complete class

The dictionary should set what to take as the index and what to take as the value,

//Dictionaries
 Dictionary<string, Student> stuDic = new Dictionary<string, Student>();
   //Set what is used as the index and what is used as the value / / the person name is used as the index type, and the student is used as the value type
    for (int i = 0; i < 100; i++)
 {
    Student stu = new Student();
    stu.Name = "s_" + i.ToString();
    stu.Score = 100+i;
    stuDic.Add(stu.Name,stu);
            }

Student number6 = stuDic["s_6"];
Console.WriteLine(number6.Score);

   class Student
    {
        public string Name;
        public int Score;
    }

Post + +: in case of assignment, first assign the value to the variable on the left of the equal sign, and then perform self addition (the obtained value comes first, and the self addition comes later)

typeof: view the internal structure of the type and the basic information of the data type

//typeof
    class TypeofEx
    {
        public void typeint()
        {
            Type t = typeof(int);
            Console.WriteLine(t.Namespace);
            Console.WriteLine(t.FullName);
            Console.WriteLine(t.Name);
            Console.WriteLine(t.Name);
            int c = t.GetMethods().Length;
            foreach (var mi in t.GetMethods())
            {
                Console.WriteLine(mi.Name);
            }
            Console.WriteLine(c);
        }
    }

Default: gets the default value of the type

Structure (value type), enumeration type (value type), reference type,

When default is found to be a structure type, it will return a value of 0 in the memory block, and the default value of the reference type is null

Value, null;

When enumerating types, the values returned in the memory block are all 0, so whoever is the first in the enumerating type is the one returned;

When the enumeration type displays assignment, it returns the type whose assignment is 0. When there is no 0 value in the display assignment, an error may occur, so it is recommended

When defining, a value of 0 is specially assigned to exist;

//default
    class DefaultEx
    {
        public void ShowDefault()
        {
             int x = default(int);//When default is found to be a structure type, it will return a value of 0 in the memory block
            Console.WriteLine(x);//Reference type default value is null
            Level level = default(Level);
            Console.WriteLine(level);//If all values in the returned memory block are 0, the first one in the enumeration type is the one returned
            Level2 level2= default(Level2);
            Console.WriteLine(level2);//When the assignment is displayed, the type of assignment that is 0 is returned,
        }
        enum Level
        {
            Low,
            Mid,
            High
        }
        enum Level2  //When there is no 0 value in the display assignment, an error may occur, so it is recommended to assign a 0 value to the definition
        {
            Low=1,
            Mid=0,
            High=2
        }

    }

var: the value type is not clear for the time being, which is determined according to the assignment

New: create an instance in memory and immediately call its instance constructor. If there is an assignment symbol on the left of new, it will get it

The instance memory address, which has used the assignment operator, is given to the assignment variable responsible for accessing;

You can also call the instance initializer: {}, and immediately set its value for the instance property

It is not necessary to call the new operator when creating an instance: new is required for class type creation. When unifying basic types, (string) is hidden

new operator; array type is similar;

Anonymous type creation object: the named type (form, etc.) is a non anonymous type. For non anonymous types, new needs to be followed by

A type name; using VAR gives full play to all the functions of var.

Implicit type variables to implicit instances;

//Anonymous type
    class anonmous
    {
        //anonmous an1 = new anonmous();
        //an1.anonmousShow();
        public void anonmousShow()
        {
            Form form1 = new Form();//The non anonymous type / / anonymous class forms a strong coupling with the Form class
        //Anonymous depends on form class. Form class is abnormal, and anonymous class cannot be used normally
            var person = new { Name = "myhello", age = 34 };//Anonymous type, inferred by the compiler
            Console.WriteLine(person .age);
            Console.WriteLine(person .Name);
            Console.WriteLine(person .GetType().Name);
        }
    }

Once new is called in a class, the type being written and the type creating the instance form a very strong coupling;

Design pattern: dependency injection pattern: helps us to loosely couple tight coupled programming

new keyword versatility: modifier. It is used in inheritance. It is similar to overriding the parent method. The child class hides the parent method

//new as modifier
    class Student
    {
        public void Report()
        {
            Console.WriteLine("Im a student!");
        }        
    }

    class CsStudent:Student
    {
        new public void Report()//The child class hides the parent class method, and new is the modifier
        {
            Console.WriteLine("Im a Csstudent!");
        }
    }

checked: whether a value overflows in memory (strongly typed language. The function of data type is to indicate that the type can be used in memory

The size of the occupied space determines its range. Exceptions can be used to catch.

Unchecked: unchecked mode is adopted by C# default

uint: unsigned integer

//
 class CheckShow
    {

        //CheckShow check1 = new CheckShow();
        //check1.showuint2();

        public void showuint()
        {
            uint x = uint.MaxValue;
            Console.WriteLine(x);
            string binStr = Convert.ToString(x, 2);
            Console.WriteLine(binStr);
        }

        public void showuint2()//Exception capture
        {
            uint x = uint.MaxValue;
            Console.WriteLine(x);
            try
            {
                uint y = checked(x + 1);//It will be reminded at compile time
                Console.WriteLine(y);
            }
            catch (OverflowException ex)
            {

                Console.WriteLine("there is overflow!");
            }
        }
        public void showuint3()
        {
            uint x = uint.MaxValue;
            Console.WriteLine(x);
            string binStr = Convert.ToString(x, 2);
            Console.WriteLine(binStr);
            checked//Within the scope of its statement block, all overflows can be detected / / or marked as undetected and unchecked
            {
                try
                {
                    uint y = checked(x + 1);//It will be reminded at compile time
                    Console.WriteLine(y);
                }
                catch (OverflowException ex)
                {

                    Console.WriteLine("there is overflow!");
                }
            }
        }
    }

delegate: rarely used, generates anonymous methods, and attaches the event handler to the event through the + = operator

If it will not be reviewed later, it is not necessary to make it a method, and you can use anonymous methods to handle it

sizeof: used to obtain basic data types, structure data types (except string and object), and can be used to obtain custom data types

The number of bytes of data type in memory

//
    class UseSizeof
    {
        private bool x;

        struct student
        {
            int Id;
            long Score;
        }
        public void ShowSizeof()
        {
            unsafe
            {
             int x = sizeof(student);//Use unsafe to obtain the size of a custom structure
             Console.WriteLine(x);
            }
        }
    }

 ->: Take the address symbol. C # has a real pointer to directly operate the memory, so it should be placed in unsafe (unsafe)

(hereinafter) (pointer operation, address fetching operation, and accessing member operations with pointers can only operate structure types, not them

Use. Access is direct access, and use pointer access is indirect access.

//
    class Useend
    {
        struct student
        {
            public int Id;
            public long Score;
        }
        public void ShowEnd()
        {
            unsafe
            {
                student stu;
                stu.Id = 1;
                stu.Score = 99;
                student* pStu = &stu;
                pStu->Score = 100;//Using pointers is indirect access
                (*pStu).Score = 1000;//It is also an access to its address
                Console.WriteLine(stu.Score );//Use. Is direct access
            }
        }
    }

Unary operator: one operand can be used

&: take the address operator and give it to the pointer variable

Positive and negative operators: Note overflow

~: inverse operator, which performs bitwise negation on binary;

Pre auto increment: add before use

Post auto increment: used first and then added

Cast type:

Implicit type conversion: the code does not explicitly tell the compiler to convert types: there are three types (without losing precision, and the subclass is converted to the parent class)

(if the plug-in object is of type object, the compiler must be told what type it needs to be converted to, and it must be converted to display.)

Conversion without loss of precision: (long 8 bytes, int 4 bytes, 32 bits, int to long conversion, precision will not be lost)

  From left to right, no progress or accuracy is lost

Subclass to parent conversion: (supported by all object-oriented programming)

The stored address can be assigned in the form of assignment. When trying to access the referenced member with a reference variable, you can only

The member of the type accessing the variable, not the type of the instance

//Implicit type conversion
   class ShowConvert2
    {
        public void sh2()
        {

        }
    }
    class ShowConvert
    {
        //ShowConvert sc1 = new ShowConvert();
        //sc1.showConvert3();
        public void  showConvert1()
        {
            string str1 = Console.ReadLine();//Enter data from the control window
            string str2 = Console.ReadLine();
            int x = Convert.ToInt32(str1);
            int y = Convert.ToInt32(str2);//Convert to 32-bit shaping
            Console.WriteLine(x+y);//Any operator is inseparable from the data type
        }

        public void showConvert2()
        {
            int x = int.MaxValue;
            long y = x;//Implicit conversion without losing progress
            Console.WriteLine(y);
        }

        class Animal
        {
            public void Eat()
            {
                Console.WriteLine("Eating ");
            }
        }
        class Human:Animal
        {
            public void Think()
            {
                Console.WriteLine("Im thinking");
            }
        }

        class Teacher:Human
        {
            public void Teach()
            {
                Console.WriteLine("Im teaching");
            }
        }

        public void showConvert3()
        {
            Teacher t = new Teacher();
            Human h = t;//teacher can be assigned to human, the address stored by T is given to h, and the transformation from subclass to parent class
                        //There is no teach method in h, and only the methods of variable types can be accessed
                        //The tl stores the address of the instance of the teacher type,
                        //When you try to access a member referenced by a reference variable, you can only access the member of the variable's type, not the instance's type
                        //There are think and eat in the human class, so h only these two methods, although they refer to the instance of teacher
            Animal a = h;
            a.Eat();
        }

Display type conversion:

Tells the compiler to convert one type to another

In order to solve this problem, there may be loss of precision or errors in type conversion, so you need to tell the compiler

Cast: cast. Use the type conversion operator () to put the large number of bytes into the small ones, and only keep the low and high ones

go

Convert: there is a large gap between types (string is converted to int, etc.) convert class (string is converted to numeric type)

Numerical classes have their own instance method tostring, and can also convert numerical classes into string classes (when displaying numerical values in text boxes)

The target type has tryParse: the conversion success is true, and the failure is false

Display type conversion is a constructor of the target type in the converted type

  Data type promotion: when double and int types are calculated, the result will become double type. Double type has higher precision and can ensure

Accuracy is not lost

Integer division, floating-point type division,

In binary, shifting 2 to the left is multiplying 2, and shifting 2 to the right is dividing 2 (without overflow)

For a left shift, 0 is added for a negative number and 1 is added for a positive number

Relational operator: compare numeric type and character type (char type corresponds to uicode and has corresponding data value) (ratio size)

Strings can only compare equality and inequality

string.Compare method, equal to 0 is equal, negative value 1 < 2, two strings are aligned, and uicode codes are compared one by one

var result = t is Teacher;//Check whether t is true or false returned by teacher

Check whether t is true or false returned by teacher

A parent class can be verified as a child class, but a child class cannot be verified as a parent class

 object o = new Teacher();
 Teacher t1 = o as Teacher;//O if you are like a teacher, give the address to o, otherwise return t1 a null

&&: condition and: if both sides are true, you get true, otherwise it is false

||: condition or: as long as there is a ture, the result is ture

With short-circuit effect: sometimes only the first half is executed, and the second half will not be executed (sometimes the second half will be executed)

Nullable type: nullable int type

            Nullable<int> x = null;//null assignable integer
            x = 100;//You can assign values later
            Console.WriteLine(x);
            Console.WriteLine(x.HasValue);//True is returned if there is a value, false is returned if there is a null value
 int ?x = null;//Nullable keyword, equivalent to nullable < int >
                          // x = 100;
 int y = x ?? 1;//If y is null, give 1

Conditional operator:

            int x = 80;
            // string str = string.Empty;
            //  STR = x > = 60? "Pass": "failed"; / / greater than 60 returns to the left of the colon, otherwise it returns to the right of the colon
            string str =( x >= 60) ? "pass" : "failed";//Conditions can be enclosed with () to improve readability
            Console.WriteLine(str);
int x = 7;
            x <<= 2;//x=x<<2
            Console.WriteLine(x);
            int a = 5;
            int b = 6;
            int c = 7;
            int d = a += b *= c;//All assignment operators, from right to left, calculate b=b*c first

Tags: C#

Posted on Thu, 23 Sep 2021 03:59:03 -0400 by DigitHeads