天天看點

c#入門 學習筆記

  1. Hello World
    //列印語句
    Console.WriteLine("Hello World");
    //暫停
    Console.ReadKey();
               
  2. 資料類型

    1.值類型 byte,char,short,int,long,bool,decimal,float,double,sbyte,uint,ulong,ushort

    2.引用類型: 儲存的不是值實際資料而是一個記憶體位址 object、dynamic 和 string。

    3.對象類型:Object 類型檢查是在編譯時發生的

    4.動态類型: 可以存儲任何類型的值在動态資料類型變量中,類型檢查在運作時

    5.字元串(String)類型

    6.指針類型(Pointer types)

  3. 類型轉換
    1. 隐式轉換
    2. 顯式轉換
    3. Toxxx方法
  4. 變量
  5. 常量
    1. 整數常量
      • 整數常量可以是十進制、八進制或十六進制的常量。字首指定基數:0x 或 0X 表示十六進制,0 表示八進制,不帶字首則預設表示十進制。
      • 整數常量也可以帶一個字尾,字尾是 U 和 L 的組合,U 表示無符号整數(unsigned),L 表示長整數(long)。字尾可以是大寫,也可以是小寫,U 和 L 的順序任意。
    2. 浮點常量(小數必須包含整數)
    3. 字元常量
    4. 字元串常量
    5. 定義常量
  6. 運算符
    1. 算數運算符
    2. 關系運算符
    3. 邏輯運算符
    4. 位運算符
    5. 指派運算符
    6. 其他運算符
      1. sizeof():資料類型的大小
      2. typeof():傳回 class的類型。
      3. &: 傳回變量的位址
      4. *:變量的指針
      5. ?: :三元表達式
      6. is:判斷對象是否為某一類型
      7. as: 強制轉換,即使失敗也不會抛出異常
  7. 判斷:
    1. if
    2. switch
  8. 循環:
    1. while循環
    2. for/foreach
    3. do…while
  9. 封裝:
    1. public:允許一個類将其成員變量和成員函數暴露給其他的函數和對象。任何公有成員可以被外部的類通路
    2. private:允許一個類将其成員變量和成員函數對其他的函數和對象進行隐藏。隻有同一個類中的函數可以通路它的私有成員。即使是類的執行個體也不能通路它的私有成員。
    3. protected:該類内部和繼承類中可以通路。
    4. internal:同一個程式集的對象可以通路。
    5. protected internal:3 和 4 的并集,符合任意一條都可以通路。
  10. 可空類型

    //預設值為0

    int a;

    //預設值為null

    int? b=123;

    //如果b為null就指派2否則c=b

    int c= b?? 2;

    Console.WriteLine(“c的值為{0}”, c);

    Console.ReadLine();

  11. 數組
    //初始化數組逐個指派
    int[] arr = new int[10];
    arr[0] = 12312;
    //初始化數組并指派
    int[] arr1 = { 321, 312, 12312, 12312312, 12312312 };
    //使用for循環指派
    for (int i = 0; i < 10; i++)
    {
    arr[i] = i + 100;
    }
    //使用forEach取值
    foreach (int i in arr)
    {
    Console.WriteLine("元素的值為{0}", i);
    }
               
  12. 結構體
    struct Books{
    public string id;
    public string name;
    public string price;
    }
    static void Main()
    {
    Books book1;
    book1.id = "123";
    book1.name = "aaa";
    book1.price = "23131";
    Console.WriteLine("書資訊:書id{0},書名{1},書價格{2}",book1.id,book1.name,book1.price);
    Console.ReadLine();
    }
               
    • 類與結構的不同點
      1. 類是引用類型,結構是值類型
      2. 結構不支援繼承
      3. 結構不能聲明預設的構造函數
      4. 結構體中無法執行個體屬性或賦初始值
    • 類與結構的選擇
      1. 當我們描述一個輕量級對象的時候,結構可提高效率,成本更低。資料儲存在棧中,通路速度快
      2. 當堆棧的空間很有限,且有大量的邏輯對象或者表現抽象和多等級的對象層次時,建立類要比建立結構好一些;
  13. 枚舉
    //枚舉清單中的每個符号代表一個整數值,一個比它前面的符号大的整數值,可自定義每個符号
    enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
    static void Enum()
    {
    int a = (int)Days.Wed;
    Console.WriteLine(a);
    Console.ReadLine();
    }	
               
  14. 析構函數
    class Test
    {
        string id;
        public Test()
        {
            Console.WriteLine("構造函數");
        }
        ~Test()
        {
            Console.WriteLine("析構函數");
        }
        static void Main()
        {
            Test test = new Test { id = "123" };
            Console.WriteLine("id為{0}", test.id);
            Console.ReadLine();
        }
    
    }
               
  15. 多态性
    1. 通過在類定義前面放置關鍵字 sealed,可以将類聲明為密封類。當一個類被聲明為 sealed 時,它不能被繼承。抽象類不能被聲明為 sealed。
    2. 當有一個定義在類中的函數需要在繼承類中實作時,可以使用虛方法。虛方法是使用關鍵字 virtual 聲明的。虛方法可以在不同的繼承類中有不同的實作。
  16. 運算符的重載
    class Test2
        {
            public int length;
            //運算符重載  
            public static Test2 operator +(Test2 a, Test2 b)
            {
                Test2 test = new Test2 { length = a.length - b.length };
                return test;
            }
            static void Main(string[] args)
            {
                Test2 test = new Test2 { length = 12 };
                Test2 test1 = new Test2 { length = 213 };
                Test2 t = test + test1;
                Console.WriteLine("t的值{0}", t.length);
                Console.ReadLine();
            }
        }
               
  17. 預處理器指令
    1. #define 預處理器
    2. 條件指令
  18. 異常處理
    1. try catch finally
    2. 常見異常:
      1. IO異常
      2. 空對象
      3. 類型轉換
      4. 除以0
  19. 檔案的輸入與輸出
    //位元組流讀取檔案
     static void Main(string[] args)
     {
     StreamReader streamReader =new StreamReader(@"D:\Document\test.txt");
     string line;
     //讀取檔案内容
     while ((line = streamReader.ReadLine()) != null)
     {
     //列印出來
     Console.WriteLine(line);
     }
     Console.ReadLine();
     }
               
  20. windows檔案系統操作
    static void Main(string[] args) {
            GetFile(@"D:\ProgramFiles");
            Console.ReadLine();
        }
        //獲得某檔案夾下的檔案名與大小
        static void GetFile(String path) {
            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            DirectoryInfo[] directoryInfo1 = directoryInfo.GetDirectories();
            FileInfo[] files = directoryInfo.GetFiles();
            if(directoryInfo1!=null) {
                foreach(DirectoryInfo directoryInfo2 in directoryInfo1) {
                    if(directoryInfo2.Name!="app") {
                        GetFile([email protected]"\"+directoryInfo2.Name);
                    }
                }
            }
            if(files!=null) {
                foreach(FileInfo file in files) {
                    Console.WriteLine("檔案名:{0},檔案大小{1}",file.Name,file.Length);
                }
            }
        }
               
  21. 特性
    1. 預定義特性

      1.AttributeUsage

      2.Conditional

      3.Obsolete:

      [Obsolete("過時了")]

      編譯器會給出警告資訊

      [Obsolete("過時了",true)]

      編譯器會給出錯誤資訊
    2. 自定義特性
  22. 委托
    delegate void ConsoleWrite1();
    namespace ConsoleApp1 {
        class Program {
    
            static void Main(string[] args) {
                ConsoleWrite1 consoleWrite1 = new ConsoleWrite1(ConsoleWrite);
                consoleWrite1();
                Console.ReadLine();
            }
            static void ConsoleWrite() {
                Console.WriteLine("測試");
            }
               
    • 委托的用途
      static FileStream fs;
      static StreamWriter sw;
      // 委托聲明
      public delegate void printString(string s);
      
      // 該方法列印到控制台
      public static void WriteToScreen(string str) {
          Console.WriteLine("The String is: {0}",str);
      }
      // 該方法列印到檔案
      public static void WriteToFile(string s) {
          fs=new FileStream(@"D:\Document\test.txt",
          FileMode.Append,FileAccess.Write);
          sw=new StreamWriter(fs);
          sw.WriteLine(s);
          sw.Flush();
          sw.Close();
          fs.Close();
      }
      // 該方法把委托作為參數,并使用它調用方法
      public static void sendString(printString ps) {
          ps("Hello World");
      }
      static void Main(string[] args) {
          printString ps1 = new printString(WriteToScreen);
          printString ps2 = new printString(WriteToFile);
          sendString(ps1);
          sendString(ps2);
          Console.ReadKey();
      }
                 
    1. 指針變量
      static unsafe void Test12() {
      int i = 0;
      int* p = &i;
      Console.WriteLine("i的值為{0},記憶體位址為{1}",i,(int)p);
      Console.WriteLine();
      }
                 
    2. 傳遞指針作為方法的參數
      static unsafe void Main() {
          int var1 = 10;
          int var2 = 20;
          Console.WriteLine("var1:{0},var2:{1}",var1,var2);
          int* a = &var1;
          int* b = &var2;
          Swap(a,b);
          Console.WriteLine("var1:{0},var2:{1}",var1,var2);
          Console.ReadLine();
      }
      static unsafe void Swap(int* a,int* b) {
          int temp =*a;
          *a=*b;
          *b=temp;
      }
                 
    3. 使用指針通路數組元素
      static unsafe void array() {
       	           int[] list = { 10,100,200 };
       	           fixed (int* ptr = list)
      	              /* 顯示指針中數組位址 */
      	              for(int i = 0;i<3;i++) {
      	                  Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr+i));
      	              Console.WriteLine("Value of list[{0}]={1}",i,*(ptr+i));
              }
      	      Console.ReadKey();
                 
  23. out參數:一個方法傳回多個不同類型的參數
    static void Main() {
        string s="asd";
        int i=Test7(out s);
        Console.WriteLine(s);
        Console.WriteLine(i);
        Console.ReadLine();
    
    }
    
    public static int Test7(out string a) {
        a="asddddddddddd";
        return 1;
    }
    
               
  24. params參數
    static void Main() {
            Params(213,31231,12312,13231,123,1312,312,312,321,3,12,312,12);
        }
        static void Params(params int[] array) {
            int max = array[0];
            for(int i = 0;i<array.Length;i++) {
                if(array[i]>max) {
                    max=array[i];
                }
            }
            Console.WriteLine("最大值為{0}",max);
            Console.ReadLine();
        }
               
  25. ref參數
    static void Main() {
            int i = 30;
            Ref(ref i);
            Console.WriteLine(i);
            Console.ReadKey();
        }
        static void Ref(ref int a) {
            a+=500;
        }
               
  26. 連接配接資料庫
    static void MysqlConnection() {
            //配置連接配接資訊
            String connstr = "server=localhost;port=3306;user=root;password=123456;database=ztree";
            MySqlConnection mySqlConnection = new MySqlConnection(connstr);
            //打開連接配接
            mySqlConnection.Open();
            //sql語句
            string sql = "select * from city";
            MySqlCommand mySqlCommand = new MySqlCommand(sql,mySqlConnection);
            //執行sql語句
            MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
            while(mySqlDataReader.Read()) {
                if(mySqlDataReader.HasRows) {
                    Console.WriteLine("id:{0};name:{1};pid:{2}",mySqlDataReader.GetString(0),mySqlDataReader.GetString(1),mySqlDataReader.GetString(2));
                }
            }
            mySqlConnection.Close();
        }