耿鴨玩轉C#之基礎語法

0. 簡介

C# 語言是微軟推出的一款面向對象的編程語言,憑藉其通用的語法和便捷的使用方法受到了很多企業和開發人員的青睞。

C# 語言具備了面嚮對象語言的特徵,即封裝、繼承、 多態,並且添加了事件和委託,增強了編程的靈活性。

Visual Studio 2015 是專門的一套基於組件的開發工具,主要用於 .NET 平臺下的軟件開發,C# 語言作爲 .NET 平臺下的首選編程語言,在該開發工具下可以開發控制檯應用程序、Windows 窗體應用程序、ASP.NET 網站程序等。

1. Hello,world!

以下步驟演示瞭如何創建一個C#的Hello world程序:

  1. 打開Visual Studio 2019
  2. 選擇“創建新項目”
  3. 語言選擇“C#”
    在這裏插入圖片描述
  4. 選擇“控制檯應用”
    在這裏插入圖片描述
  5. 配置項目名稱和解決方案名稱
  6. 創建項目
  7. 編寫代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, world!");
            Console.WriteLine("中文也\"可\"!");
            Console.Write("我不換行");
            Console.Write("我不換行");
        }
    }
}
  1. 點擊“調試->開始執行(不調試)”,得到運行結果
    在這裏插入圖片描述

2. 數據類型

在C#中,變量被分爲以下幾種類型:

  • 值類型
  • 引用類型
  • 指針類型

2.1 值類型

下表列出了可用的值類型:
注意三個特殊的——decimal、sbyte、long
在這裏插入圖片描述
如同C++一樣,可以使用 sizeof 來獲取某個類型的存儲尺寸。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Size of int: {0}", sizeof(int));  // 4
            Console.WriteLine("Size of long: {0}", sizeof(long));  // 8
            Console.WriteLine("Size of bool: {0}", sizeof(bool));  // 1
        }
    }
}

2.2 引用類型

引用類型不包含存儲在變量中的實際數據,但它們包含對變量的引用。
換句話說,它們指的是一個內存位置。使用多個變量時,引用類型可以指向一個內存位置。如果內存位置的數據是由一個變量改變的,其他變量會自動反映這種值的變化。內置的引用類型有:object、dynamic 和 string

2.2.1 對象(Object)類型

對象(Object)類型是所有類型的基類。Object 是 System.Object 類的別名。所以對象(Object)類型可以被分配任何其他類型(值類型、引用類型、預定義類型或用戶自定義類型)的值。但是,在分配值之前,需要先進行類型轉換。
當一個值類型轉換爲對象類型時,則被稱爲裝箱;另一方面,當一個對象類型轉換爲值類型時,則被稱爲拆箱

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            object obj;

            // 裝箱
            obj = 13;
            Console.WriteLine(obj);

            // 拆箱
            int x = (int)obj;
            Console.WriteLine(x);

            // 拆箱拋出異常
            double y = (double)obj;  // System.InvalidCastException
            Console.WriteLine(y);
        }
    }
}

2.2.2 動態(Dynamic)類型

說白了,動態類型就是把C#當成Python玩。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            dynamic a = 3;
            Console.WriteLine(a);
            a = "haha";
            Console.WriteLine(a);
            a.shit();  // 編譯時不報錯,執行到這一句時報錯
        }
    }
}

2.1.2 字符串類型

字符型只能存放一個字符,它佔用兩個字節,能存放一個漢字。C#內部存儲爲UTF-16編碼,即每個字符用兩個字節存儲。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            char a = '耿';
            char b = '鴨';
            string c = "厲害!";
            Console.Write(a);
            Console.Write(b);
            Console.WriteLine(c);
        }
    }
}

在這裏插入圖片描述
如果在字符串前加@,就如同Python裏的原始字符串。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            string str1 = @"I am \gh\";
            string str2 = @"haha
            hehe
            xixi";

            Console.WriteLine(str1);
            Console.WriteLine(str2);
        }
    }
}

在這裏插入圖片描述

2.3 指針類型

指針類型變量存儲另一種類型的內存地址。C# 中的指針與 C 或 C++ 中的指針有相同的功能。將在"不安全的代碼"中討論指針類型。

2.4 類型轉換

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            int a = 123456;

            // 顯示類型轉換
            double b = a;

            // 隱式類型轉換
            int c = (int)b;

            // 轉換爲string
            string str = a.ToString();

            // string轉換回int
            int d = int.Parse(str);  // 轉換失敗則拋出System.FormatException

            Console.WriteLine(d);
        }
    }
}

3. 運算符

以下着重介紹sizeof、is、as,其他運算符與Java類似,故省略。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            // 返回數據類型的大小
            int a = sizeof(long);

            // 判斷對象是否爲某一類型
            bool b = a is int;
            bool c = a is long;

            // 強制類型轉換
            // 如果轉換失敗,將返回null,而不是異常
            object x = 123;
            string y = x as string;
            Console.WriteLine(y is null);
        }
    }
}

4. 變量

與Java類似,因此僅給出一個示例:

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            int var1 = 100;
            double var2 = 100.123;
            bool var3 = true;
            String var4 = "耿鴨";

            Console.WriteLine("var1 = " + var1);
            Console.WriteLine("var2 = " + var2);
            Console.WriteLine("var3 = " + var3);
            Console.WriteLine("var4 = " + var4);
        }
    }
}

在這裏插入圖片描述

5. 常量

常量使用關鍵詞const定義:

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            const double PI = 3.14;

            Console.WriteLine(PI);
        }
    }
}

注意:const在編譯時確定值,因此不能引用變量,如以下寫法是錯誤的:

int a = 3;
const int b = a + 1;

對於**@加在字符串常量之前**,可參見2.1.2節。

6. 判斷和循環

if、switch、for、while、do-while、break、continue與Java完全相同,故不加贅述。

7. 面向對象

面嚮對象語言的三大特徵分別是封裝、繼承、多態。(而不是wyh說的那些個orz)

7.1 訪問修飾符

類的訪問修飾符主要有兩個:public和internal(可省略)
類中成員的訪問修飾符有四個:

  1. public
    成員可以被任何代碼訪問。
  2. private
    成員僅能被同一個類中的代碼訪問,如果在類成員前未使用任何訪問修飾符,則默認爲private
  3. internal
    成員僅能被同一個項目中的代碼訪問。
  4. protected
    成員只能由類或派生類中的代碼訪問。派生類是在繼承中涉及的。

除此之外,還有修飾符:

  • readonly:使用 readonly 修飾字段意味着只能讀取該字段的值而不能給字段賦值,只能在聲明或構造函數中初始化
  • static:使用 static 修飾的字段是靜態字段,可以直接通過類名訪問該字段。

以下給出一個示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Student {
        string name;
        public readonly int age = 21;
        public bool sex;

        public static int haha = 24;
        static int hehe = 13;
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student();

            /* 以下打了註釋的行均會報錯 */
            // stu.name = "";
            // stu.age = 21;
            Console.WriteLine(stu.age);
            // Console.WriteLine(Student.hehe);
            Console.WriteLine(Student.haha);
        }
    }
}

7.2 方法

屬性的命名規則爲Pascal命名法,即單詞首字母大寫。(示例中忘了這一點orz)
方法的定義與Java類似,以下給出一個示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Student {
        string name;
        int age = 21;

        public void setName(string name) {
            this.name = name;
        }

        public string getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student();
            Console.WriteLine(stu.getAge());
            stu.setName("鴨鴨");
            Console.WriteLine(stu.getName());
            // Console.WriteLine(stu.name);
        }
    }
}

7.3 屬性(get/set訪問器)

屬性的命名規則爲Pascal命名法,即單詞首字母大寫。
get訪問器和set訪問器指定了讀取和修改屬性時的行爲。兩者省略哪一個都行。
以下給出一個示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Student {
        string name;
        bool sex;

        public string Name {
            get {
                return name;
            }

            set {
                name = value;
            }
        }

        public int Age {
            get {
                return 22;
            }
        }

        public bool Sex {
            set {
                sex = value;
            }
        }
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student();

            /* 以下打了註釋的行均會報錯 */
            stu.Name = "耿耿";
            Console.WriteLine(stu.Name);
            // stu.Age = 22;
            Console.WriteLine(stu.Age);
            stu.Sex = true;
            // Console.WriteLine(stu.Sex);
        }
    }
}

如果是隻讀屬性,還可以採用以下快速寫法:

class Student {
    public string Name { get; } = "耿耿";
}

7.4 構造方法

與Java基本相同,見以下示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Student {
        public string name;
        public int age;

        public Student(string name) : this(name, 20) {
        }

        public Student(string name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student("耿耿", 20);
            Student stu2 = new Student("犇犇~");
        }
    }
}

7.5 析構方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Student {
        public string name;
        public int age;

        public Student(string name) {
            this.name = name;
        }

        ~Student() {
            Console.WriteLine(name + ",我人沒了~");
        }
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student("耿鴨");
            {  // 從結果看這個大括號沒什麼影響orz
                Student stu2 = new Student("哥哥");
            }
            Student stu3 = new Student("犇犇");
        }
    }
}

在這裏插入圖片描述

7.6 重載

懶得講了orz。

7.7 引用類型參數ref和out

總體來說,ref和out差別不大,都表示引用傳遞。但是out的變量可以不賦初始值,而ref一定要賦初始值。

using System;

namespace ConsoleApp1 {
    class Program {
        static void swap(ref int a, ref int b) {
            int temp = a;
            a = b;
            b = temp;
        }

        static void calc(out int res) {
            res = 5;
        }

        static void Main(string[] args) {
            int a = 3, b = 22;

            swap(ref a, ref b);

            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);

            int res;
            calc(out res);

            Console.WriteLine("res = " + res);
        }
    }
}

在這裏插入圖片描述

7.8 內部類和靜態類

靜態類是不能實例化的類,其中只能有靜態成員。
內部類相當於類中的成員。
注意,內部類與外部類沒什麼關係,只是掛一個名字而已。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class OuterClass {
        public class Student {
            public string name;
            public int age;
        }

        public static class Teacher {
            public static string name;
        }
    }

    class Program {
        static void Main(string[] args) {
            OuterClass.Student stu = new OuterClass.Student();
            stu.age = 20;
            // OuterClass.Teacher t = new OuterClass.Teacher();
            OuterClass.Teacher.name = "haha";
        }
    }
}

7.9 繼承

與Java一樣,C#不支持多重繼承,但是可以實現多個接口。
此外,以下示例還演示了調用父類的構造方法

using System;

namespace ConsoleApp1 {
    class Person {
        public string name;

        public void Introduce() {
            Console.WriteLine("你好,我是{0}", name);
        }

        public Person() { }

        public Person(string name) {
            this.name = name;
        }
    }

    class Student : Person {
        public void SayHello() {
            Console.WriteLine("我是學生{0}", name);
        }
    }

    interface ILearner {
        void Learn();
    }

    // 不能繼承多個類
    // class Teacher : Person, Student { }

    // 可以繼承一個類和實現多個接口
    class Teacher : Person, ILearner {
        public void Learn() {
            Console.WriteLine("我是{0},我愛學習!", name);
        }

        // 調用父類的構造方法(base)
        public Teacher(string name) : base(name) { }
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student();
            stu.name = "耿鴨";
            stu.Introduce();
            stu.SayHello();

            Teacher teacher = new Teacher("耿老師");
            teacher.Learn();
        }
    }
}

7.10 多態

實現多態要確保以下兩點,缺一不可:

  • 父類定義虛方法
  • 子類重寫父類的方法

示例:

using System;

namespace ConsoleApp1 {
    class Person {
        public string name;

        public Person(string name) {
            this.name = name;
        }

        // 父類定義虛方法
        public virtual void Introduce() {
            Console.WriteLine("你好,我是{0}", name);
        }
    }

    class Student : Person {
        public Student(string name) : base(name) { }

        // 子類重寫父類的方法
        public override void Introduce() {
            Console.WriteLine("你好,我是學生{0}", name);

            // 調用父類的方法
            base.Introduce();
        }
    }

    class Program {
        static void Main(string[] args) {
            Student stu = new Student("耿鴨");
            stu.Introduce();
            Person stu2 = new Student("菜鴨");
            stu2.Introduce();
        }
    }
}

在這裏插入圖片描述

7.11 運算符重載

以下是C#中可重載的運算符:
在這裏插入圖片描述
示例:

using System;

namespace ConsoleApp1 {
    class MyString {
        public string str;

        public MyString(string str) {
            this.str = str;
        }

        public static MyString operator *(MyString s, int times) {
            string res = "";
            while (times-- > 0) {
                res += s.str;
            }
            return new MyString(res);
        }
    }

    class Program {
        static void Main(string[] args) {
            MyString s1 = new MyString("耿鴨~");
            MyString s2 = s1 * 3;
            Console.WriteLine(s2.str);
            // MyString s3 = 3 * s1;

            // *= 運算符自動調用重載後的 * 方法
            s1 *= 4;
            Console.WriteLine(s1.str);
        }
    }
}

7.12 接口

C#中的接口與Java類似,故不加贅述。需要特別說明的是接口的命名規範是以“I”字母打頭。

8. 可空類型

對於int、double、bool這些類型,無法賦值爲null,而可空類型使得這一操作得以實現。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            string str = null;  // √
            // int a = null;  // ×
            int? a = null;
            Console.WriteLine(a);  // nothing
            Console.WriteLine(a == null);  // True
            a += 2;
            Console.WriteLine(a == null);  // True

            // ??運算符將null替代爲默認值
            int? b = 123;
            int aa = a ?? 1;
            int bb = b ?? 1;
            Console.WriteLine("{0}, {1}", aa, bb);  // 1, 123
        }
    }
}

9. 數組

9.1 一維數組

與Java中的一維數組的使用類似,下面給出創建並初始化數組的三種方法:

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            // 方法一
            int[] arr = new int[3];
            Console.WriteLine(arr[0]);  // 0
            Console.WriteLine(arr[1]);  // 0
            Console.WriteLine(arr[2]);  // 0
            arr[0] = arr[1] = arr[2] = 999;
            // Console.WriteLine(arr[3]);  // System.IndexOutOfRangeException

            // 方法二
            int[] arr2 = { 2, 3, 5, 7 };
            Console.WriteLine(arr2.Length);  // 4

            // 方法三
            int[] arr3;
            arr3 = new int[] { 2, 3, 4, 8 };
            Console.WriteLine(arr3.Length);  // 4
        }
    }
}

9.2 使用foreach遍歷數組

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            int[] arr = new int[5];
            for (int i = 0; i < arr.Length; ++i) {
                arr[i] = 10 + i;
            }
            foreach (int val in arr) {
                Console.WriteLine(val);
            }
        }
    }
}

9.3 多維數組

多維數組是與Java中的多維數組不同的。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            // 初始化
            int[,] arr = {
                { 2, 3, 5 },
                { 7, 11, 13 },
            };
            Console.WriteLine(arr.Length);  // 6
            Console.WriteLine(arr.GetLength(0));  // 2
            Console.WriteLine(arr.GetLength(1));  // 3

            // 下標索引
            arr[0, 1]++;

            // 遍歷每個元素
            foreach (int val in arr) {
                Console.WriteLine(val);  // 2 4 5 7 11 13
            }
        }
    }
}

9.4 交錯數組

和Java中的數組使用方法類似,即數組的數組

9.5 參數數組

有時,當聲明一個方法時,您不能確定要傳遞給函數作爲參數的參數數目。C# 參數數組解決了這個問題,參數數組通常用於傳遞未知數量的參數給函數
注意,數組形參前要加上 params 關鍵字。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Sum(string name, params int[] arr) {
            int res = 0;
            foreach (int val in arr) {
                res += val;
            }
            Console.WriteLine("{0} : {1}", name, res);
        }

        static void Main(string[] args) {
            int[] arr = { 1, 2, 3, 4 };
            Sum("耿鴨", arr);
            Sum("貓貓", 1, 2, 3, 4);
        }
    }
}

在這裏插入圖片描述

9.6 Array類

Array 類是 C# 中所有數組的基類,它是在 System 命名空間中定義。Array 類提供了各種用於數組的屬性和方法。

Array類的常用屬性

在這裏插入圖片描述

Array類的常用方法

在這裏插入圖片描述

躬行

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            int[] arr = { 1, 4, 2, 8, 5, 7 };

            // 逆序
            Array.Reverse(arr);
            foreach (int val in arr) {
                Console.WriteLine(val);  // 7 5 8 2 4 1
            }

            // 搜索
            int idx = Array.IndexOf(arr, 8);
            Console.WriteLine(idx);  // 2
            idx = Array.IndexOf(arr, 9);
            Console.WriteLine(idx);  // -1

            // 排序
            Array.Sort(arr);
            foreach (int val in arr) {
                Console.WriteLine(val);  // 1 2 4 5 7 8
            }
        }
    }
}

10. 字符串

10.1 字符串的常用屬性和方法

在字符串操作中常用的屬性或方法如下表所示。
在這裏插入圖片描述
示例代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            string str = "abcd";

            // 下標索引
            char ch = str[2];
            Console.WriteLine(ch);

            // 獲取長度
            str = "耿鴨100分";
            int len = str.Length;
            Console.WriteLine(len);

            // 刪除空白字符
            str = "  \t 歸真返璞   \t\t\n";
            Console.WriteLine(str);
            string res = str.Trim();
            Console.WriteLine(res);

            // 分割字符串
            str = "你好 我叫\t耿耿";
            string[] arr = str.Split();
            Console.WriteLine(arr.Length);

            // 轉換爲char數組
            str = "abc地以負";
            char[] charr = str.ToCharArray();
            foreach(char c in charr) {
                Console.WriteLine(c);
            }
        }
    }
}

在這裏插入圖片描述

10.2 創建字符串的方法

有以下四種創建字符串的方法,其中字符串格式化名堂較多,暫不深究。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            // 1. 字符串拼接
            string str1 = "ab" + "cd" + 12 + 34;
            Console.WriteLine(str1);  // abcd1234

            // 2. 通過char數組
            char[] chs = { '你', '是', '笨', '笨' };
            string str2 = new string(chs);
            Console.WriteLine(str2.Length);  // 4
            Console.WriteLine(str2);  // 你是笨笨

            // 3. Join方法
            string[] arr = { "我是", "耿耿", "愛", "鴨鴨" };
            string str3 = String.Join(" ", arr);
            Console.WriteLine(str3);  // 我是 耿耿 愛 鴨鴨

            // 4. 字符串格式化
            string str4 = String.Format("I am {0}, my age is {1}.", "耿耿", 21);
            Console.WriteLine(str4);
        }
    }
}

11. 結構體

C#中的結構體具有以下幾個特點:

  • 結構體是值類型而不是引用類型
  • 創建結構體變量可以不使用new,此時需要手動初始化每個字段後才能訪問成員
  • 結構可定義構造函數,但不能定義析構函數。但是,您不能爲結構定義無參構造函數。無參構造函數(默認)是自動定義的,且不能被改變。
  • 結構體中聲明的字段不能賦初值
  • 構造函數中必須爲所有字段賦值

示例:

using System;

namespace ConsoleApp1 {
    struct Student {
        // 3. 結構體中聲明的字段不能賦初值
        public string name;
        // public int age = 0;
        public int age;
        public bool sex;

        // 4. 構造函數中必須爲所有字段賦值
        public Student(int x) {
            name = null;
            age = 0;
            sex = false;
        }

        public void init() {
            name = "貓貓";
            age = 21;
            sex = true;
        }

        public void introduce() {
            Console.WriteLine("大家好,我是{0},我{1}歲了!", name, age);
        }
    }

    class Program {
        static void fake(Student stu) {
            stu.name = "哈哈";
            stu.age = -1;
        }

        static void real(ref Student stu) {
            stu.name = "哈哈";
            stu.age = -1;
        }

        static void Main(string[] args) {
            // 1. 兩種創建結構體變量的方法

            // 1.1 通過new操作符,此時每個字段被初始化爲0
            Student stu = new Student();
            stu.introduce();  // 全是零值
            stu.init();
            stu.introduce();

            // 1.2 不使用new操作符,此時需要手動初始化每個字段後才能訪問成員
            Student stu2;
            // stu2.introduce();  // 報錯,因爲字段未初始化
            stu2.name = "耿鴨";
            stu2.age = 0;
            stu2.sex = false;
            stu2.introduce();

            // 2. 結構體是值類型而不是引用類型
            fake(stu2);
            stu2.introduce();  // 沒有改變
            real(ref stu2);
            stu2.introduce();  // 改變了
        }
    }
}

12. 枚舉型

枚舉是一組命名整型常量。枚舉類型是使用 enum 關鍵字聲明的。C# 中枚舉是值類型
以下給出一個示例:

using System;

namespace ConsoleApp1 {
    class Program {
        enum Day {
            Sunday, Monday, Tuesday, Webnesday, Thursday, Friday, Saturday,
        }

        static void Main(string[] args) {
            // 1. 枚舉變量的使用
            Day day = Day.Monday;
            Console.WriteLine(day);  // Monday

            // 2. 枚舉變量轉int
            // 下標默認從0開始
            int d = (int)day;
            Console.WriteLine(d);  // 1
        }
    }
}

13. 命名空間

爲了訪問命名空間,使用“.”操作符。
使用 using 關鍵字引入命名空間,也可以起別名。

不使用using的示例

using System;

namespace space1 {
    namespace space2 {
        class Student { }
    }
}

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            space1.space2.Student stu = new space1.space2.Student();
        }
    }
}

使用using的示例

using System;
using space1;
using haha = space1.space2;

namespace space1 {
    class Teacher { }

    namespace space2 {
        class Student { }
    }
}

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            Teacher t = new Teacher();
            haha.Student s1 = new haha.Student();
        }
    }
}

∞. 常用類庫簡介

Console類

C# Console 類主要用於控制檯應用程序的輸入和輸岀操作。
在這裏插入圖片描述
除此之外,還有ReadKey()方法讀取一次鍵盤敲擊。Write方法可以格式化輸出

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("請輸入一個字符:");
            int ch = Console.Read();

            Console.Read();  // 吸收換行符
            Console.Read();

            Console.WriteLine("您輸入了字符:{0}", ch);
            Console.WriteLine("請輸入一行文本:");
            string line = Console.ReadLine();
            Console.WriteLine("您輸入了文本:{0}", line);

            Console.WriteLine("請按下一個鍵:");
            ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();
            char key = consoleKeyInfo.KeyChar;
            Console.WriteLine("您按下了鍵:{0},ASCII碼爲:{1}", key, (int)key);
        }
    }
}

在這裏插入圖片描述

Math類

C# Math 類主要用於一些與數學相關的計算,並提供了很多靜態方法方便訪問,常用的方法如下表所示。
在這裏插入圖片描述

Random類

C# Math 類主要用於產生隨機數。
在這裏插入圖片描述
示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            Random rd = new Random();

            // 產生[1, 10)之間的隨機整數
            Console.WriteLine(rd.Next(1, 10));

            // 產生[0, 1)之間的隨機浮點數
            Console.WriteLine(rd.NextDouble());

            // 隨機填充字節數組
            byte[] bytes = new byte[5];
            rd.NextBytes(bytes);
            foreach (byte b in bytes) {
                Console.Write(b + " ");
            }
            Console.WriteLine();
        }
    }
}

在這裏插入圖片描述

DateTime類

不想搞了,等用到了再說粑。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章