C# study notes (2)

C# type conversion

Type conversion is to convert from one data type to another data type, there are two ways: implicit type conversion and explicit type conversion:

  • Implicit type conversion
    Implicit type conversion is the default safe conversion method of C#, which will not cause data loss. Implicit conversion includes conversion from a data type with lower precision to a data type with higher precision, or conversion from derived classes to the base class.

  • explicit type conversion

    Explicit type conversions are casts, which are implemented by using the cast operator in front of the data name.

Some examples of specific implicit and explicit conversions are shown below:

using System;

namespace TypeConversionApplication {
    
    
  class TypeConversion {
    
    
    static void Main(string[] args) {
    
    
      /* 强制类型转换 */
      float f = 3.1415926F; // 注意要加上F,不然系统会默认为食double类型的浮点数
      int i;
      
      i = (int)f;
      
      Console.WriteLine("强制类型转换");
      Console.WriteLine(f);
      Console.WriteLine(i);
      /* 强制类型转换 */
      
      /* ------------------- */
      
      /* 隐式转换 */
      float fi = 3.14159;
      double di = fi;
      Console.WriteLine();
      Console.WriteLine("隐式类型转换");
      Console.WriteLine(fi);
      Console.WriteLine(di);
      
      // 失败情况,编译器报错
      // double dis = 3.14;
      // float fis = dis;
      /* 隐式转换 */
    }
  }
}

The result of the code running is shown in the following figure. It can be observed that the forced type conversion causes data loss, but the display conversion does not, as shown in the following figure:

img1

C# itself also provides many built-in data type conversion methods, such as ToByte(), ToString(), etc., as follows:

using System;

namespace TypeConversionApplication
{
    
    
    class TypeConversion
    {
    
    
        static void Main(string[] args)
        {
    
    
            // ToString
            float f1 = 3.14159F;
            string s1 = f1.ToString();

            // ToFloat
            double d1 = Convert.ToDouble(f1);

            Console.WriteLine(s1);
            Console.WriteLine(d1);
        }
    }
}

The result of running is as follows:

img2


C# modifiers

C# has five access modifiers, as shown in the following table:

access modifier Effect
public public, public, any public members can be accessed by external classes
private Private, that is, only accessible within the current class, member variables are private by default
protected Protected, that is, it can only be accessed by methods in the current class or in subclasses
internal It can only be accessed in the current project. If the class is not modified, the default is internal
protected internal protected internal

A few things to note:

  • Class modifiers can only be public and internal
  • Subclass access rights cannot be higher than parent class access rights

C# loop

There are two main forms of for and foreach loops in C#, which can be reviewed in the following bubble sort code:

using System;

namespace CycleApplication
{
    
    
    class Calculater
    {
    
    
        static void Main(string[] args)
        {
    
    
            int[] arr = {
    
     3, 5, 2, 4, 7, 9, 8, 0, 1, 3 };
            bubbleSort(arr);
            foreach (int i in arr)
            {
    
    
                Console.Write(String.Format("{0, -2}", i));
            }
            Console.WriteLine();
        }

        static void bubbleSort(int[] arr)
        {
    
    
            for (int i = 0; i < arr.Length; i++)
            {
    
    
                for (int j = 0; j < arr.Length - i - 1; j++)
                {
    
    
                    if (arr[j] > arr[j+1])
                    {
    
    
                        int tmp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = tmp;
                    }
                }
            }
        }
    }
}

For formatted output, see https://www.cnblogs.com/arxive/p/5744823.html

Regarding the process of method invocation, it is similar to C++. Let’s learn it by hand-tearing quicksort:

using System;

namespace quickSortApplication
{
    
    
    class quickSortSet
    {
    
    
        public void swap(ref int a, ref int b)
        {
    
    
            int tmp = a;
            a = b;
            b = tmp;
        }

        public void quicksort(int[] arr, int start, int end)
        {
    
    
            if (start < end)
            {
    
    
                int i = start;
                int j = end;
                int key = arr[i];
                while (i < j)
                {
    
    
                    while (i < j && arr[j] > key)
                    {
    
    
                        j--;
                    }

                    if (i < j)
                    {
    
    
                        swap(ref arr[i], ref arr[j]);
                        i++;
                    }

                    while (i < j && arr[i] < key)
                    {
    
    
                        i++;
                    }

                    if (i < j)
                    {
    
    
                        swap(ref arr[i], ref arr[j]);
                        j--;
                    }
                }
                quicksort(arr, start, i - 1);
                quicksort(arr, i + 1, end);
            }
        }

        static void Main(string[] args)
        {
    
    
            int[] arr = {
    
     2, 3, 1, 6, 4, 8, 5, 9, 1, 0 };
            quickSortSet qs = new quickSortSet();
            qs.quicksort(arr, 0, 9);
            foreach (int i in arr)
            {
    
    
                Console.Write(String.Format("{0, -2}", i));
            }
            Console.WriteLine();
        }
    }
}

C# Nullable

Single question mark? It is used to assign data types to data types that cannot be directly assigned to null, such as int, double, and bool.

Double question mark? ? Used to determine the return value when a data is null.

Try the following example code:

using System;

namespace NullableApplication
{
    
    
    class NullableTest
    {
    
    
        static void Main(string[] args)
        {
    
    
            double? num1 = null;
            double? num2 = 3.14159;
            double num3 = 3.14;
            Console.WriteLine(num1);
            Console.WriteLine(num2);
            Console.WriteLine(num3);

            num3 = num1 ?? 5.35;
            Console.WriteLine(num3);
        }
    }
}

The execution result of the code is as follows:

img3


C# String

The best way to get started with strings is to use:

using System;

namespace StringApplication
{
    
    
    class StringApp
    {
    
    
        static void Main(String[] args)
        {
    
    
            string str1 = " I am ";
            string str2 = " Alva";

            /* Trim */
            str1 = str1.Trim();
            Console.WriteLine(String.Format("Str1 after triming: {0}", str1));

            string str3 = string.Concat(str1, str2);
            Console.WriteLine(String.Format("Concat str1 and str2: {0}", str3));

            Console.WriteLine(String.Format("Index1 : {0}", str3[0]));
            Console.WriteLine(String.Format("Find Index: {0}", str3));
            Console.WriteLine(String.Format("ToUpper: {0}", str3.ToUpper()));
            Console.WriteLine(String.Format("ToLower: {0}", str3.ToLower()));
        }
    }
}

The execution result of the code is as follows:

img9


C# enumeration

Enumeration type enum , each number in the enumeration list represents an integer value, and the value of the first enumeration symbol is 0 by default.

using System;

namespace EnumApplication {
    
    
  class EnumTest {
    
    
    enum Day {
    
    Mon, Tus, Wes, Thr, Fri, Sat, Sun};
    int Monday = (int)Day.Mon;
    Console.WriteLine(Monday);
  }
}

The execution result of the code is as follows:

img10

C# inheritance

I personally think that inheritance and polymorphism are very similar to C++, and I have written Java myself. I feel that I will write two demos by myself and I will master it sooner. C# does not support multiple inheritance, but multiple inheritance can be achieved through interfaces.

First write a piece of inherited code to play with:

using System;

namespace InheritantApplication
{
    
    
    enum Gentle {
    
     male, female };

    class Person
    {
    
    
        protected string name {
    
     get; set; }
        protected Gentle gentle {
    
     get; set; }
        protected int age {
    
     get; set; }

        public Person(string _name, Gentle _gentle, int _age)
        {
    
    
            name = _name;
            gentle = _gentle;
            age = _age;
        }
    }

    class Student : Person
    {
    
    
        protected string major {
    
     get; set; }

        public Student(string _name, Gentle _gentle, int _age, string _major) : base(_name, _gentle, _age)
        {
    
    
            major = _major;
        }

        public override string ToString()
        {
    
    
            return $"Student information: \n" +
                   $"Name  : {name}\n" +
                   $"Gentle: {gentle}\n" +
                   $"Age   : {age}\n" +
                   $"Major : {major}";
        }
    }

    class ExecuteInhritant
    {
    
    
        static void Main(string[] args)
        {
    
    
            Student student1 = new Student("Alva", Gentle.male, 22, "SE");
            string Info = student1.ToString();
            Console.WriteLine(Info);
        }
    }
}

Execute the above code, you can print out the output information you expect:

img11

The enum of C# has been tested, and it seems that it can directly output the fields when it is defined. For example, the output of Gentle.male is male. If you want to output 0, you need to do a forced type conversion.

polymorphism

Polymorphism is a common interview question in C++, so I am still familiar with it. Polymorphism mainly includes compile-time polymorphism and run-time polymorphism. Compile-time polymorphism includes function overloading and generic programming, and run-time polymorphism is The polymorphism implemented in the class is implemented through virtual functions.

abstract class

Some features of abstract classes:

  • cannot create an instance of an abstract class
  • Cannot declare abstract method outside abstract class
  • The keyword sealed in front of the class indicates that the class cannot be inherited, but the abstract class cannot be modified by sealed

Write a simple abstract class to get familiar with the syntax:

using System;

namespace InheritantApplication
{
    
    
    abstract class Animal
    {
    
    
        abstract public void bark();
    }

    class Dog : Animal
    {
    
    
        public override void bark()
        {
    
    
            Console.WriteLine("Wang Wang!");
        }
    }

    class Cat : Animal
    {
    
    
        public override void bark()
        {
    
    
            Console.WriteLine("Miao Miao!");
        }
    }

    class ExecuteAnimal
    {
    
    
        static void Main(string[] args)
        {
    
    
            Cat cat = new Cat();
            cat.bark();

            Dog dog = new Dog();
            dog.bark();
        }
    }
}

The running result of the program is as follows, which shows that polymorphism is realized:

img12

Of course, if you do not use abstract classes to achieve polymorphism, you can also use virtual functions to achieve it. The specific method is to add the virtual keyword before the corresponding functions of the base class. C# does not support multiple inheritance, so abstract classes can only be single inherit.

interface

  • If the interface inherits other interfaces, then all the methods of the inherited interface need to be implemented.
  • The name of the interface usually starts with I.
  • The interface cannot be modified with modifiers such as public and abstract, and cannot have field variables and constructors.
  • Properties can be defined within an interface.
  • Interfaces can solve the C# multiple inheritance problem.

Simple exception handling

Exception handling is basically similar to C++, and I don't have much depth myself, so I just wrote a piece of code to learn it:

using System;

namespace ExceptionApplication
{
    
    
    class MyException : Exception
    {
    
    
        public void print()
        {
    
    
            Console.WriteLine("Hellow World!");
        }
    }

    class ExecuteApp
    {
    
    
        static void Main(string[] args)
        {
    
    
            try
            {
    
    
                throw new MyException();
            }
            catch (MyException e)
            {
    
    
                e.print();
            }
            finally {
    
    
                Console.WriteLine("Hi!");
            }
        }
    }
}

img14

Reference

https://www.cnblogs.com/zsongs/p/5071748.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324064281&siteId=291194637