C# 語言程序設計筆記


C#是一種最新的、面向對象的編程語言。它使得程序員可以快速地編寫各種基於Microsoft .NET平台的應用程序,Microsoft .NET提供了一系列的工具和服務來最大程度地開發利用計算與通訊領域。他是從C和C++派生而來的,其與C/C++語法非常相似,並依附於.NET虛擬機的強大類庫支持,各方面對強於C/C++.

基本的流程控制

標准輸入輸出:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello world");
            string Str = Console.ReadLine();
            Console.WriteLine(Str);
        }
    }
}

常用變量類型:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte s_byte = 254;
            sbyte s_sbyte = 126;
            short s_short = 32766;
            int s_int = 2147483645;
            double s_double = 3.1415926;
            decimal d_decimal = 5000m;
            string s_string = "hello lyshark";
        }
    }
}

if語句:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const int x = 100;
            const int y = 200;
            int source = 0;
            Console.WriteLine("請輸入一個數:");
            source = int.Parse(Console.ReadLine());
            if (source == 0)
            {
                Console.WriteLine("你沒有輸入任何數.");
            }
            else if (source > x && source < y)
            {
                Console.WriteLine("符合規范");
            }
            Console.ReadKey();
        }
    }
}

switch

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("輸入一個整數: ");
            int score = Convert.ToInt32(Console.ReadLine());
            switch (score / 10)
            {
                case 10:
                case 9:
                    Console.WriteLine("A");break;
                case 8:
                case 7:
                    Console.WriteLine("B");break;

                default:
                    Console.WriteLine("none");break;
            }
            Console.ReadKey();
        }
    }
}

while-dowhile

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] MyArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            int index = 0;
            while (index < 10)
            {
                Console.WriteLine("數組中的值: {0}", MyArray[index]);
                index++;
            }

            index = 0;
            do
            {
                Console.Write("{0} ", MyArray[index]);
                index++;
            } while (index < 10);

            Console.ReadKey();
        }
    }
}

for

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] MyArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            for (int index = 0; index < MyArray.Length; index++)
            {
                Console.WriteLine("下標:{0} --> 數據: {1}", index, MyArray[index]);
            }

            ArrayList alt = new ArrayList();

            alt.Add("你好");
            alt.Add("世界");
            foreach (string Str in alt)
            {
                Console.WriteLine("輸出: {0}", Str);
            }

            Console.ReadKey();
        }
    }
}

break

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int x = 0; x < 5; x++)
            {
                for(int y=0; y<10 ;y++)
                {
                    if (y == 3)
                        break;
                    Console.WriteLine("輸出: {0}",y);
                }
            }
            Console.ReadKey();
        }
    }
}

goto

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] MyStr = new string[3];

            MyStr[0] = "hello";
            MyStr[1] = "world";
            MyStr[2] = "lyshark";

            for (int x = 0; x < MyStr.Length; x++)
            {
                if(MyStr[x].Equals("lyshark"))
                {
                    goto Is_Found;
                }
            }
        Is_Found:
            Console.Write("查找到成員");
            Console.ReadKey();
        }
    }
}

判斷閏年案例:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.Write("輸入年份: ");
                int year = Convert.ToInt32(Console.ReadLine());
                Console.Write("輸入月份: ");
                int month = Convert.ToInt32(Console.ReadLine());
                if (month >= 1 && month <= 12)
                {
                    int day = 0;
                    switch (month)
                    {
                        case 1:
                        case 3:
                        case 5:
                        case 7:
                        case 8:
                        case 10:
                        case 12: day = 31; break;
                        case 2:
                            if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
                                day = 29;
                            else
                                day = 28;
                            break;
                        default: day = 30; break;
                    }
                    Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
                }
            }
            catch
            {
                Console.WriteLine("異常了");
            }
            Console.ReadKey();
        }
    }
}

99口訣表

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int x = 1; x <= 9; x++)
            {
                for (int y = 1; y <= x; y++)
                {
                    Console.Write("{0} * {1} = {2} \t", y, x, x * y);
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}

枚舉類型:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    public enum QQState
    {
        OnLine = 1,
        OffLine,
        Leave,
        Busy,
        QMe
    }

    class Program
    {
        static void Main(string[] args)
        {
            QQState state = QQState.OnLine;
            // 將state強轉為整數
            int num = (int)state;
            Console.WriteLine(num);

            // 將整數強轉為枚舉類型
            int num1 = 2;
            QQState x = (QQState)num1;
            Console.WriteLine("狀態: {0}",x);

            // 輸入一個號兵輸出對應狀態
            string input = Console.ReadLine();
            switch(input)
            {
                case "1":
                    QQState s1 = (QQState)Enum.Parse(typeof(QQState), input);
                    Console.WriteLine("狀態: {0}", s1);
                    break;
            }
            Console.ReadKey();
        }
    }
}

定義結構數據:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 定義結構數據
        public struct Person
        {
            public double width;
            public double height;

            // 結構體支持構造函數
            public Person(double x, double y)
            {
                width = x;
                height = y;
            }
        }

        static void Main(string[] args)
        {
            Person per;

            per.width = 100;
            per.height = 200;
            Console.WriteLine("x = {0} y = {1}", per.width, per.height);

            Person ptr = new Person(10, 20);
            Console.WriteLine("x = {0} y = {1}", ptr.width, ptr.height);

            Console.ReadKey();
        }
    }
}

遍歷文件目錄:

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Director(string dir) 
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
            try
            {
                foreach (FileSystemInfo fsinfo in fsinfos)
                {
                    if (fsinfo is DirectoryInfo)     //判斷是否為文件夾
                    {
                        Director(fsinfo.FullName);//遞歸調用
                    }
                    else
                    {
                        Console.WriteLine(fsinfo.FullName);//輸出文件的全部路徑
                    }
                }
            }
            catch { }
        }

        static void Main(string[] args)
        {
            Director(@"d:\\");
            Console.ReadKey();
        }
    }
}

序列化/反序列化:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        [Serializable]
        public struct Person
        {
            public string name;
            public int age;

            public Person(string _name, int _age) 
            {
                this.name = _name;
                this.age = _age;
            }
        }

        static void Main(string[] args)
        {
            // 開始序列化
            Person ptr = new Person("lyshark",22);
            using (FileStream fWrite = new FileStream(@"c:\save.json", FileMode.OpenOrCreate, FileAccess.Write))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fWrite, ptr);
            }

            // 反序列化
            Person read_ptr;
            using (FileStream fsRead = new FileStream(@"C:\save.json", FileMode.OpenOrCreate, FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
                read_ptr = (Person)bf.Deserialize(fsRead);
            }
            Console.WriteLine("姓名: " + read_ptr.name);
            Console.ReadKey();
        }
    }
}

文件讀寫:

using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            // 寫入文件
            using (FileStream fsWrite = new FileStream(@"C:\test.log", FileMode.OpenOrCreate, FileAccess.Write))
            {
                for(int x=0;x<100;x++)
                {
                    string str = "你好世界 \n";
                    byte[] buffer = Encoding.UTF8.GetBytes(str);
                    fsWrite.Write(buffer, 0, buffer.Length);
                }
            }

            // 從文件中讀取數據
            FileStream fsRead = new FileStream(@"C:\test.log", FileMode.OpenOrCreate, FileAccess.Read);
            byte[] buffer1 = new byte[1024 * 1024 * 5];
            int r = fsRead.Read(buffer1, 0, buffer1.Length);
            //將字節數組中每一個元素按照指定的編碼格式解碼成字符串
            string s = Encoding.UTF8.GetString(buffer1, 0, r);

            fsRead.Close();
            fsRead.Dispose();
            Console.WriteLine(s);

            Console.ReadKey();
        }
    }
}

逐行讀取數據:

using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            //使用StreamWriter來寫入一個文本文件
            using (StreamWriter sw = new StreamWriter(@"C:\test.txt", true))
            {
                for (int x = 0; x < 10;x++ )
                {
                    sw.Write("追加寫入數據 \n");
                }
            }

            // 每次讀取一行
            using (StreamReader sw = new StreamReader(@"C:\test.txt", true))
            {
                for (int x = 0; x < 10; x++)
                {
                    string str = sw.ReadLine();
                    Console.WriteLine(str);
                }
            }
            Console.ReadKey();
        }
    }
}

文件拷貝: 先將要復制的多媒體文件讀取出來,然后再寫入到你指定的位置

using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        public static void CopyFile(string soucre, string target)
        {
            // 我們創建一個負責讀取的流
            using (FileStream fsRead = new FileStream(soucre, FileMode.Open, FileAccess.Read))
            {
                // 創建一個負責寫入的流
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    // 因為文件可能會比較大,所以我們在讀取的時候 應該通過一個循環去讀取
                    while (true)
                    {
                        // 返回本次讀取實際讀取到的字節數
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        // 如果返回一個0,也就意味什么都沒有讀取到,讀取完了
                        if (r == 0)
                        {
                            break;
                        }
                        fsWrite.Write(buffer, 0, r);
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            string source = @"c:\save.json";
            string target = @"c:\cpy.json";

            CopyFile(source, target);
            Console.ReadKey();
        }
    }
}

文件路徑獲取:

using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = @"C:\save.json";
            //獲得文件名
            Console.WriteLine(Path.GetFileName(str));
            //獲得文件名但是不包含擴展名
            Console.WriteLine(Path.GetFileNameWithoutExtension(str));
            //獲得文件的擴展名
            Console.WriteLine(Path.GetExtension(str));
            //獲得文件所在的文件夾的名稱
            Console.WriteLine(Path.GetDirectoryName(str));
            //獲得文件所在的全路徑
            Console.WriteLine(Path.GetFullPath(str));
            //連接兩個字符串作為路徑
            Console.WriteLine(Path.Combine(@"c:\a\", "b.txt"));

            int index = str.LastIndexOf("\\");
            str = str.Substring(index + 1);
            Console.WriteLine(str);

            Console.ReadKey();
        }
    }
}

創建刪除文件:

using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //創建一個文件
            File.Create(@"C:\test.log");
            Console.WriteLine("創建成功");
            Console.ReadKey();

            //刪除一個文件
            File.Delete(@"C:\test.log");
            Console.WriteLine("刪除成功");
            Console.ReadKey();

            //復制一個文件
            File.Copy(@"C:\test.log", @"C:\new.txt");
            Console.WriteLine("復制成功");
            Console.ReadKey();

            //剪切
            File.Move(@"C:\test.log", @"C:\new.txt");
            Console.WriteLine("剪切成功");
            Console.ReadKey();

            Console.ReadKey();
        }
    }
}

二進制文件存取:

using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 字節寫入數據
            string s = "今天天氣好晴朗,處處好風光";
            // 將字符串轉換成字節數組
            byte[] buffer=  Encoding.Default.GetBytes(s);
            ////以字節的形式向計算機中寫入文本文件
            File.WriteAllBytes(@"C:\1.txt", buffer);

            // 字節讀取數據
            byte[] read_buf = File.ReadAllBytes(@"C:\1.txt");
            EncodingInfo[] en = Encoding.GetEncodings();
            // 將字節數組轉換成字符串
            string read_str = Encoding.Default.GetString(read_buf);
            Console.WriteLine(read_str);

            Console.ReadKey();
        }
    }
}

靜態與動態數組

C#中的數組是由System.Array類衍生出來的引用對象,因此可以使用Array類中的各種方法對數組進行各種操作。

一維數組:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 定義一維數組
            int[] IntArray = new int[10] {1,2,3,4,5,6,7,8,9,10};

            // 定義一維字符串數組
            string[] StrArray = new string[3];

            StrArray[0] = "abc" ;
            StrArray[1] = "abc";

            Console.ReadKey();
        }
    }
}

刪除元素(一維數組):

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 定義一維數組
            int[] IntArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            // 遍歷數組
            foreach (int num in IntArray)
                Console.WriteLine(num);
            Console.ReadLine();

            // 通過循環刪除第三個元素
            int Del_Num = 2;
            for (int x = Del_Num; x < IntArray.Length - Del_Num; x++)
            {
                IntArray[x] = IntArray[x - 1];
            }
            Console.ReadKey();
        }
    }
}

尋找最大最小值:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 定義一維數組
            int[] Array = new int[10] { 57, 32, 78, 96, 33, 11, 78, 3, 78, 2 };

            // 聲明兩個變量用來存儲最大值和最小值
            int min = int.MaxValue;
            int max = int.MinValue;
            int sum = 0;

            for (int i = 0; i < Array.Length; i++)
            {
                if (Array[i] > max)
                    max = Array[i];

                if (Array[i] < min)
                    min = Array[i];

                sum += Array[i];
            }
            Console.WriteLine("最大值: {0} 最小值: {1} 總和: {2} 平均值: {3}", max, min, sum, sum / Array.Length);
            Console.ReadKey();
        }
    }
}

數組組合為字符串:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] name = { "老楊", "老蘇", "老鄒", "老虎", "老牛", "老馬" };
            string str = null;

            for (int x = 0; x < name.Length - 1; x++)
                str += name[x] + "|";

            Console.WriteLine(str + name[name.Length - 1]);

            Console.ReadKey();
        }
    }
}

數組元素反轉:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] name = { "老楊", "老蘇", "老鄒", "老虎", "老牛", "老馬" };
            string tmp;

            for (int x = 0; x < name.Length / 2; x++)
            {
                tmp = name[name.Length - 1 - x];
                name[x] = name[name.Length - 1 - x];
                name[name.Length - 1 - x] = tmp;
            }

            for (int x = 0; x < name.Length - 1; x++)
                Console.Write(name[x] + " |"  );

            Console.ReadKey();
        }
    }
}

冒泡排序:

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


namespace ConsoleApplication1
{
    class Program
    {
        // 執行排序
        static void Sort(int[] Array)
        {
            for (int x = 0; x < Array.Length - 1; x++)
            {
                for (int y = 0; y < Array.Length - 1 - x; y++)
                {
                    if (Array[y] > Array[y + 1])
                    {
                        int tmp = Array[y];
                        Array[y] = Array[y + 1];
                        Array[y+1] = tmp;
                    }
                }
            }
        }

        // 輸出結果
        static void Display(int[] Array)
        {
            for (int x = 0; x < Array.Length; x++)
            {
                Console.Write(Array[x] + " ");
            }
        }

        static void Main(string[] args)
        {
            int[] MyArray = new int[10] { 57, 32, 4, 96, 33, 11, 78, 3, 78, 2 };

            Sort(MyArray);
            Display(MyArray);

            // 使用系統提供的方法排序
            Array.Sort(MyArray);
            // 執行一次反向排序
            Array.Reverse(MyArray);

            Console.ReadKey();
        }
    }
}

直接插入排序:

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


namespace ConsoleApplication1
{
    class Program
    {
        // 執行排序
        static void Sort(int[] Array)
        {
            for (int x = 0; x < Array.Length; x++)
            {
                int tmp = Array[x];
                int y = x;
                while ((y > 0) && (Array[y - 1] > tmp))
                {
                    Array[y] = Array[y-1];
                    --y;
                }
                Array[y] = tmp;
            }
        }

        static void Main(string[] args)
        {
            int[] MyArray = new int[10] { 57, 32, 4, 96, 33, 11, 78, 3, 78, 2 };

            Sort(MyArray);

            foreach (int x in MyArray)
                Console.Write(x + " ");

            Console.ReadKey();
        }
    }
}

選擇排序:

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


namespace ConsoleApplication1
{
    class Program
    {
        // 執行排序
        static void Sort(int[] Array)
        {
            int min = 0;
            for (int x = 0; x < Array.Length; x++)
            {
                min = x;

                for (int y = x + 1; y < Array.Length; y++)
                {
                    if (Array[y] < Array[min])
                        min = y;
                }

                int tmp = Array[min];
                Array[min] = Array[x];
                Array[x] = tmp;
            }
        }

        static void Main(string[] args)
        {
            int[] MyArray = new int[10] { 57, 32, 4, 96, 33, 11, 78, 3, 78, 2 };

            Sort(MyArray);

            foreach (int x in MyArray)
                Console.Write(x + " ");

            Console.ReadKey();
        }
    }
}

定義二維數組

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 定義二維數組
            int[,] Array = new int[2,3]{{1,2,4},{4,5,6}};

            Console.WriteLine("數組行數為: {0}", Array.Rank);
            Console.WriteLine("數組列數為: {0}", Array.GetUpperBound(Array.Rank - 1) + 1);

            for (int x = 0; x < Array.Rank;x++ )
            {
                string str = "";
                for(int y=0;y< Array.GetUpperBound(Array.Rank-1)+1;y++)
                {
                    str = str + Convert.ToString(Array[x, y]) + " ";
                }
                Console.Write(str);
            }
            Console.ReadKey();
        }
    }
}

定義動態二維數組:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int Row = Convert.ToInt32(Console.ReadLine());
            int Col = Convert.ToInt32(Console.ReadLine());

            int[,] Array = new int[Row, Col];

            for (int x = 0; x < Row; x++)
            {
                for (int y = 0; y < Col; y++)
                {
                    Console.Write(x + "-->" + y.ToString() + " ");
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}

一維數組的合並:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Array1 = new int[] { 1, 2, 3, 4, 5 };
            int[] Array2 = new int[] { 6, 7, 8, 9, 10 };

            // 將Array1 與 Array2 合並成 Array3
            int Count = Array1.Length + Array2.Length;
            int[] Array3 = new int[Count];

            for (int x = 0; x < Array3.Length; x++)
            {
                if (x < Array1.Length)
                    Array3[x] = Array1[x];
                else
                    Array3[x] = Array2[x - Array1.Length];
            }

            foreach (int each in Array3)
                Console.Write(each + "  ");
            
            Console.ReadKey();
        }
    }
}

二維數組的合並:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Array1 = new int[] { 1, 2, 3, 4, 5 };
            int[] Array2 = new int[] { 6, 7, 8, 9, 10 };

            // 將兩個一維數組,合並到一個二維數組中
            int[,] Array3 = new int[2, 5];

            // Rank = 二維數組中的2
            for (int x = 0; x < Array3.Rank; x++)
            {
                switch (x)
                {
                    case 0:
                        {
                            for (int y = 0; y < Array1.Length; y++)
                                Array3[x, y] = Array1[y];
                            break;
                        }
                    case 1:
                        {
                            for (int z = 0; z < Array2.Length; z++)
                                Array3[x, z] = Array2[z];
                            break;
                        }
                }
            }

            // 輸出二維數組中的數據
            for (int x = 0; x < Array3.Rank;x++ )
            {
                for(int y=0;y<Array3.GetUpperBound(Array3.Rank-1)+1;y++)
                    Console.Write(Array3[x, y] + " ");
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}

二維數組的拆分:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] Array = new int[2, 3] { { 1, 3, 5 }, { 3, 4, 6 } };

            int[] ArrayOne = new int[3];
            int[] ArrayTwo = new int[4];

            for (int x = 0; x < 2; x++)
            {
                for(int y= 0; y<3; y++)
                {
                    switch(x)
                    {
                        case 0: ArrayOne[y] = Array[x, y]; break;
                        case 1: ArrayTwo[y] = Array[x, y]; break;
                    }
                }
            }

            foreach (int each in ArrayOne)
                Console.WriteLine(each);

             Console.ReadKey();
        }
    }
}

ArrayList 類位於System.Collections命名空間下,它可以動態添加和刪除元素,可以將該數組類看作擴充了功能的數組。

動態數組創建:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 動態創建 ArrayList 並初始化10個數據
            ArrayList List = new ArrayList(10);
            for (int x = 0; x < 9; x++)
                List.Add(x);

            Console.WriteLine("可包含元素數量: {0} ", List.Capacity);
            Console.WriteLine("實際包含數量: {0}", List.Count);

            foreach (int each in List)
                Console.Write(each + " ");
            Console.WriteLine();

            // 將普通數組添加到ArrayList中
            int[] Array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            ArrayList List1 = new ArrayList(Array);
            for (int x = 0; x < List1.Count; x++)
                Console.Write(List1[x] + "  ");

            Console.ReadKey();
        }
    }
}

增加/插入/刪除元素:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Display(ArrayList x)
        {
            foreach (int each in x)
                Console.Write(each + "  ");
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            // 動態創建 ArrayList
            ArrayList List = new ArrayList(10);

            // 像數組增加數據
            List.Add(100);
            List.Add(200);
            List.Add(300);
            List.Add(400);
            List.Add(500);
            Display(List);

            // 插入數據
            List.Insert(1, 1000);
            List.Insert(2, 2000);
            Display(List);

            // 移除指定元素
            List.Remove(1000);
            Display(List);

            // 根據索引移除元素
            List.RemoveAt(1);
            Display(List);

            // 判斷集合中是否包含指定元素
            bool ret = List.Contains(100);
            Console.WriteLine(ret);

            // 移除一個范圍,從下標1開始向后移除3個元素
            List.RemoveRange(1, 3);
            Display(List);

            // 清空所有集合
            List.Clear();
            Console.ReadKey();
        }
    }
}

生成隨機數存入集合:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            // 創建集合,添加數字,求平均值與和,最大值,最小值
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            int sum = 0;
            int max = (int)list[0];

            for (int x = 0; x < list.Count;x++ )
            {
                if((int)list[x] > max)
                    max = (int)list[x];
                sum += (int)list[x];
            }
            Console.WriteLine("最大值: {0} 總和: {1} 平均值: {2}",max,sum,sum/list.Count);

            list.Clear();
            // 用來生成隨機數,並去重后放入list鏈表中
            Random rand = new Random();
            for (int x = 0; x < 10;x++ )
            {
                int num = rand.Next(0,10);
                // 判斷集合中是否有這個隨機數
                if (!list.Contains(num))
                    list.Add(num);
                else
                    x--;
            }
            foreach (int each in list)
                Console.WriteLine(each);

            Console.ReadKey();
        }
    }
}

增加並遍歷數組: 我們可以直接將多個數組放入到ArrayList容器中,進行存儲。

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            
            // 直接追加匿名數組
            list.Add(new int[] { 1, 2, 3, 4, 5 });
            list.Add(new int[] { 6, 7, 8, 9, 10 });

            // 定義並追加數組
            int[] ptr = new int[5] { 100, 200, 300, 400, 500 };
            list.Add(ptr);

            for (int x = 0; x < list.Count;x++ )
            {
                if (list[x] is int[])
                {
                    for(int y=0; y < ((int[])list[x]).Length; y++)
                    {
                        Console.Write(((int[])list[x])[y] + "   ");
                    }
                    Console.WriteLine();
                }
            }
            Console.ReadKey();
        }
    }
}

增加遍歷結構體:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        public struct Student
        {
            public int u_id;
            public string u_name;
            public int u_age;

            public Student(int id, string name, int age)
            {
                this.u_id = id;
                this.u_name = name;
                this.u_age = age;
            }
        }

        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();

            // 定義三個結構
            Student stu1 = new Student(1001,"admin",22);
            Student stu2 = new Student(1002, "guest", 33);
            Student stu3 = new Student(1003, "lyshark", 19);

            // 將結構追加到鏈表
            list.Add(stu1);
            list.Add(stu2);
            list.Add(stu3);

            // 遍歷結構體
            for (int x = 0; x < list.Count;x++ )
            {
                if (list[x] is Student)
                {
                    Student ptr = (Student)list[x];
                    Console.WriteLine("ID: {0} 姓名: {1} 年齡: {2}", ptr.u_id, ptr.u_name, ptr.u_age);
                }
            }

           Console.ReadKey();
        }
    }
}

隊列的使用:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue queue = new Queue();

            // 入隊
            for (int x = 0; x < 10;x++ )
            {
                queue.Enqueue(x);
                Console.WriteLine("{0} 入隊 -> 隊列計數: {1}", x,queue.Count);
            }
            // 遍歷隊列
            foreach(int each in queue)
            {
                Console.WriteLine("隊列開始: {0} --> 隊列元素: {1}", queue.Peek().ToString(),each);
            }
            // 彈出隊列
            while(queue.Count !=0)
            {
                int value = (int)queue.Dequeue();
                Console.WriteLine("{0} 出隊列.", value);
            }

           Console.ReadKey();
        }
    }
}

棧操作:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stack = new Stack();

            // 向棧追加數據
            for (int x = 0; x < 10; x++)
                stack.Push(x);

            // 查詢棧
            Console.WriteLine("當前棧頂元素為:{0}", stack.Peek().ToString());
            Console.WriteLine("移出棧頂元素:{0}", stack.Pop().ToString());
            Console.WriteLine("當前棧頂元素為:{0}", stack.Peek().ToString());

            // 遍歷棧
            foreach (int each in stack)
                Console.WriteLine(each);

            // 出棧
            while(stack.Count !=0)
            {
                int pop = (int)stack.Pop();
                Console.WriteLine("{0} 出棧", pop);
            }

            Console.ReadKey();
        }
    }
}

hash表的使用 Hashtable 哈希表,他表示鍵值對的一個集合,這些鍵值對根據鍵的哈希代碼進行組織,鍵不可以為空,值可以為空。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable hash = new Hashtable();

            // 添加鍵值對 key = value
            hash.Add("id", 1001);
            hash.Add("name", "lyshark");
            hash.Add("sex", "男");
            Console.WriteLine("hash 元素個數: {0}", hash.Count);

            // 移除一個hash值
            hash.Remove("sex");

            // 根據hash查找 是否存在
            Console.WriteLine("根據key查找: {0}", hash.Contains("name"));
            Console.WriteLine("根據key查找: {0}", hash.ContainsValue("lyshark"));

            // 遍歷hash表
            foreach (DictionaryEntry each in hash)
                Console.WriteLine(each.Key + "\t" + each.Value);
            Console.WriteLine();

            // 清空hash表
            hash.Clear();

            Console.ReadKey();
        }
    }
}

有序哈希表 SortedList 類代表了一系列按照鍵來排序的鍵/值對,這些鍵值對可以通過鍵和索引來訪問。

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList student = new SortedList();

            // 向序列追加集合
            student.Add("1001", "Lucy");
            student.Add("1002", "Lily");
            student.Add("1003", "Tom");

            // 先判斷是否存在某個值然后咋追加
            if (!student.ContainsValue("LyShark"))
                student.Add("1004", "LyShark");

            // 遍歷學生數據
            foreach(DictionaryEntry each in student)
            {
                string id = each.Key.ToString();
                string name = each.Value.ToString();
                Console.WriteLine("ID: {0} 姓名: {1}", id, name);
            }

            // 刪除一個數據
            student.Remove("1001");

            // 獲取鍵的集合
            ICollection key = student.Keys;
            foreach(string each in key)
            {
                Console.WriteLine(each + "--> " + student[each]);
            }

            Console.ReadKey();
        }
    }
}

泛型類型集合: 效率更高更快,不發生裝箱,拆箱等。

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創建泛型集合對象
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(2);
            list.Add(3);

            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 });
            list.AddRange(list);

            // List泛型集合可以轉換為數組
            int[] array = list.ToArray();
            Console.WriteLine("數組成員數: {0}", array.Length);


            // 字符數組轉換為泛型集合
            char[] chs = new char[] { 'a', 'b', 'c' };
            List<char> list_char = chs.ToList();
            Console.WriteLine("字符數組成員數: {0}",list_char.Count);

            Console.ReadKey();
        }
    }
}

k-v泛型集合: 使用隊組,實現的泛型集合。

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dict = new Dictionary<int, string>();

            dict.Add(1, "張三");
            dict.Add(2, "李四");
            dict.Add(3, "王五");

            foreach(KeyValuePair<int,string> each in dict)
            {
                Console.WriteLine("序號:{0} 數值:{1}", each.Key, each.Value);
            }

            foreach(var each in dict.Keys)
            {
                Console.WriteLine("序號:{0} 數值:{1}", each, dict[each]);
            }

            Console.ReadKey();
        }
    }
}

k-v泛型集合: 統計指定的一個字符串中單詞的出現頻率。

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String str = "welcome to china";
            // 對組統計出每個字符串出現的次數
            Dictionary<char, int> dict = new Dictionary<char, int>();
            for (int x = 0; x < str.Length;x++ )
            {
                if (str[x] == ' ')
                    continue;
                //如果dic已經包含了當前循環到的這個鍵
                if (dict.ContainsKey(str[x]))
                    dict[str[x]]++;
                // 這個字符在集合當中是第一次出現
                else
                    dict[str[x]] = 1;
            }

            // 遍歷出數量
            foreach(KeyValuePair<char,int> each in dict)
            {
                Console.WriteLine("字母: {0} 出現了: {1} 次", each.Key, each.Value);
            }

            Console.ReadKey();
        }
    }
}

k-v集合的排序:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dic = new Dictionary<int, string> { };

            dic.Add(0, "1111");
            dic.Add(1, "2222");
            dic.Add(9, "3333");
            dic.Add(3, "5555");

            Console.WriteLine("從小到大排列");
            Dictionary<int, string> dic1Asc = dic.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            foreach(KeyValuePair<int,string>key in dic1Asc)
            {
                Console.WriteLine("key: {0} Value: {1}", key.Key, key.Value);
            }

            Console.WriteLine("大到小排序");
            Dictionary<int, string> dic1desc = dic.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
 
            foreach (KeyValuePair<int, string> k in dic1desc)
            {
                Console.WriteLine("key:" + k.Key + " value:" + k.Value);
            }

            Console.ReadKey();
        }
    }
}

字符字符串操作

格式化字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string Str1 = "hello lyshark";

            // 取出字符串中指定的字符
            char Str2 = Str1[1];

            Console.WriteLine("字符: {0} 轉大寫: {1} 轉小寫: {2}", Str2, Char.ToUpper(Str2), Char.ToLower(Str2));
            Console.WriteLine("是否為數字: {0} 是否為大寫: {1} 是否為小寫: {2}",
                Char.IsNumber(Str2), Char.IsUpper(Str2), Char.IsLower(Str2));

            // 將字符串轉化為字符數組
            char[] chs = Str1.ToCharArray();

            for (int x = 0; x < chs.Length - 1; x++)
                Console.Write("{0} ", chs[x]);
            Console.WriteLine();

            // 將字符數組轉化為字符串
            string Str3 = new string(chs);
            Console.WriteLine(Str3);

            // 格式化輸出字符串
            string Str4 = "hello";
            string Str5 = "lyshark";

            string new_str = String.Format("{0},{1}", Str4, Str5);
            Console.WriteLine("格式化后的字符串: {0}", new_str);

            Console.ReadKey();
        }
    }
}

比較字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string Str1 = "hello lyshark";
            string Str2 = "hello world";
            string Str3 = "hello lyshark";

            // Compare 比較字符串,相等返回0不相等返回-1
            Console.WriteLine("Str1 比較 Str2 " + String.Compare(Str1, Str2));
            Console.WriteLine("Str1 比較 Str3 " + String.Compare(Str1, Str3));

            // Compare To 比較字符串
            Console.WriteLine("Str1 比較 Str2 " + Str1.CompareTo(Str2));
            Console.WriteLine("Str1 比較 Str3 " + Str1.CompareTo(Str3));

            // Equals 比較字符串
            Console.WriteLine("Str1 比較 Str2 " + Str1.Equals(Str2));
            Console.WriteLine("Str1 比較 Str3 " + String.Equals(Str1,Str3));

            Console.ReadKey();
        }
    }
}

截取/分割字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 從第一個位置開始截取3個字符
            string Str1 = "hello lyshark";
            string Str2 = "";

            Str2 = Str1.Substring(1, 3);
            Console.WriteLine("截取數據: {0}", Str2);

            // 分割字符串變量
            string Str3 = "用^一生#下載,百度網盤,資源";
            char[] separator = { '^', '#', ',' };         // 定義分割字符

            String[] split_string = new String[100];
            split_string = Str3.Split(separator);

            for (int x = 0; x < split_string.Length;x++ )
            {
                Console.WriteLine("切割計數: {0} 切割字符串: {1}", x, split_string[x]);
            }

            // 針對時間的切割方法
            string str = "2019-12-12";
            char[] chs = { '-' };

            string[] date = str.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine("{0}年 {1}月 {2}日", date[0], date[1], date[2]);

            Console.ReadKey();
        }
    }
}

插入/刪除字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 插入字符串的演示
            string Str1 = "下載";
            Str1 = Str1.Insert(0, "用一生時間");
            Console.WriteLine(Str1);

            string Str2;
            Str2 = Str1.Insert(Str1.Length, "百度網盤里面的資源");
            Console.WriteLine(Str2);

            // 填充字符串的演示
            string Str3;
            Str3 = Str1.PadLeft(Str1.Length + 3, '*');    // 在左側填充
            Console.WriteLine("左側填充: " + Str3);
            Str3 = Str1.PadRight(Str1.Length + 3, '*');   // 在右側填充
            Console.WriteLine("右側填充: " + Str3);

            // 去空格的實現
            string str = "            hahahah          ";
            str = str.Trim();
            str = str.TrimStart();
            str = str.TrimEnd();

            // 刪除字符串的演示
            Console.WriteLine("從索引3處向后刪除: " + Str3.Remove(3));
            Console.WriteLine("刪除指定個數的字符: " + Str3.Remove(1, 3));

            Console.ReadKey();
        }
    }
}

拷貝替換字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 普通的拷貝字符串
            string Str1 = "hello lyshark";
            string Str2;
            Str2 = string.Copy(Str1);
            Console.WriteLine("普通拷貝: " + Str2);

            // 替換字符串
            string Str3 = "one world,one dream";
            string Str4 = Str3.Replace(',','*');
            Console.WriteLine("將,替換為** => " + Str4);

            string Str5 = Str3.Replace("one", "One");
            Console.WriteLine("將one替換為One =>" + Str5);

            Console.ReadKey();
        }
    }
}

尋找開頭結尾字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "今天天氣好晴朗,處處好風光";

            // 尋找字符串開頭結尾
            if (str.StartsWith("今") && str.EndsWith("光"))
                Console.WriteLine("ok");

            // 從指定字符開始搜索,並返回位置
            int index = str.IndexOf("天氣", 0);
            Console.WriteLine(index);

            // 從結束位置開始搜索
            string path = @"c:\a\b\c蒼\d\e蒼\f\g\\fd\fd\fdf\d\vfd\蒼老師.wav";
            int path_index = path.LastIndexOf("\\");
            Console.WriteLine(path_index);

            Console.ReadKey();
        }
    }
}

串聯字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Join 將指定字符串使用|串聯起來
            string name_str = string.Join("|", "張三", "李四", "王五", "趙六", "田七");
            Console.WriteLine(name_str);

            // 將字符串切割后串聯去掉豎線
            String[] u_name = { "張三", "李四" ,"王五"};
            string ptr = string.Join("|", u_name);
            Console.WriteLine("合並后: " + ptr);

            string[] strNew = ptr.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine("去掉| = " + strNew[1]);

            for (int x = 0; x < strNew.Length;x++ )
                Console.WriteLine("去掉豎線 [{0}] = {1}",x,strNew[x]);
            
            Console.ReadKey();
        }
    }
}

字符串倒序輸出:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "hello lyshark";
            
            // 實現反轉字符串 hello -> olleh
            char[] chs = str.ToCharArray();

            for (int x = 0; x < chs.Length / 2;x++ )
            {
                char tmp = chs[x];
                chs[x] = chs[chs.Length - 1 - x];
                chs[chs.Length - 1 - x] = tmp;
            }
            str = new string(chs);
            Console.WriteLine("反轉后的結果: {0}", str);

            // 實現反轉單詞 hello lyshark -> lyshark hello
            string str1 = "hello lyshark";

            string[] strNew = str1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int x = 0; x < strNew.Length / 2; x++)
            {
                string tmp = strNew[x];
                strNew[x] = strNew[strNew.Length - 1 - x];
                strNew[strNew.Length - 1 - x] = tmp;
            }
            str1 = string.Join(" ", strNew);
            Console.WriteLine("反轉后的結果: {0}", str1);

            Console.ReadKey();
        }
    }
}

IndexOf搜索字符串:

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 通過indexOf 切割特定字符
            string email = "admin@blib.cn";
            int index = email.IndexOf("@");

            string userName = email.Substring(0, index);
            string userHost = email.Substring(index + 1);

            Console.WriteLine("名字: {0} 主機: {1}",userName,userHost);

            // 尋找指定字符出現位置
            string str = "abcd wwabcd asdcdsac waascd ascsaaa";
            int index1 = str.IndexOf('a');
            int count = 1;

            while(index1 != -1)
            {
                count++;
                index1 = str.IndexOf('a', index1 + 1);
                if (index1 == -1)
                    break;

                Console.WriteLine("第{0}次出現a的位置是{1}", count, index1);
            }

            Console.ReadKey();
        }
    }
}

字符串生成MD5:

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {

        public static string GetMD5(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] buffer = Encoding.GetEncoding("GBK").GetBytes(str);
            byte[] MD5Buffer = md5.ComputeHash(buffer);
            string strNew = "";

            for (int i = 0; i < MD5Buffer.Length; i++)
            {
                strNew += MD5Buffer[i].ToString("x2");
            }
            return strNew;
        }

        static void Main(string[] args)
        {

            Console.WriteLine(Guid.NewGuid().ToString());
            Console.WriteLine(GetMD5("123123"));
            Console.ReadKey();
        }
    }
}

使用正則表達式

校驗數字的表達式: 常用的針對數字的匹配符號。

Regex(@"^[0-9]*$");                       // 匹配0-9數字
Regex(@"^\d{n}$");                        // 匹配出現過n次的數字
Regex(@"^\d{n,}$");                       // 匹配至少出現過n次的數字
Regex(@"^\d{m,n}$");                      // 匹配最小出現過m次最大n次的數字
Regex(@"^(0|[1-9][0-9]*)$");              // 匹配零和非零開頭的數字
Regex(@"^([1-9][0-9]*)+(.[0-9]{1,2})?$"); // 匹配非零開頭的最多帶兩位小數的數字
Regex(@"^(\-)?\d+(\.\d{1,2})?$");         // 匹配帶1-2位小數的正數或負數
Regex(@"^(\-|\+)?\d+(\.\d+)?$");          // 匹配正數、負數、和小數
Regex(@"^[0-9]+(.[0-9]{2})?$");           // 匹配有兩位小數的正實數
Regex(@"^[0-9]+(.[0-9]{1,3})?$");         // 匹配有1~3位小數的正實數

Regex(@"^[1-9]\d*$");                     // 匹配非零的正整數                 
Regex(@"^([1-9][0-9]*){1,3}$");           // 同上
Regex(@"^\+?[1-9][0-9]*$");               // 同上

Regex(@"^\-[1-9][]0-9"*$);                // 匹配非零負整數
Regex(@"^-[1-9]\d*$");

Regex(@"^\d+$");                          // 匹配非負整數
Regex(@"^[1-9]\d*|0$");
Regex(@"^-[1-9]\d*|0$");                  // 匹配非正整數
Regex(@"^((-\d+)|(0+))$");

Regex(@"^(-?\d+)(\.\d+)?$");              // 匹配浮點數
Regex(@"^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$");

Regex(@"^\d+(\.\d+)?$");                  // 匹配非負浮點數
Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$");

Regex(@"^((-\d+(\.\d+)?)|(0+(\.0+)?))$"); // 匹配非正浮點數
Regex(@"^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$");

Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$")     // 匹配正浮點數
Regex(@"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$");

Regex(@"^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$"); // 匹配負浮點數
Regex(@"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$");

校驗字符的表達式

Regex(@"^[\u4e00-\u9fa5]{0,}$");          // 匹配漢字
Regex(@"^[A-Za-z0-9]+$");                 // 匹配英文和數字
Regex(@"^[A-Za-z0-9]{4,40}$");            // 匹配應為和數字,最小4位最大40位
Regex(@"^.{3,20}$");                      // 匹配長度為3-20的所有字符

Regex(@"^[A-Za-z]+$");                    // 匹配由26個英文字母組成的字符串
Regex(@"^[A-Z]+$");                       // 匹配由26個大寫英文字母組成的字符串
Regex(@"^[a-z]+$");                       // 匹配由26個小寫英文字母組成的字符串
Regex(@"^[A-Za-z0-9]+$");                 // 匹配由數字和26個英文字母組成的字符串
Regex(@"^\w+$ 或 ^\w{3,20}$");            // 匹配由數字、26個英文字母或者下划線組成的字符串

Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");     // 匹配中文、英文、數字包括下划線
Regex(@"^[\u4E00-\u9FA5A-Za-z0-9]+$");      // 匹配中文、英文、數字但不包括下划線等符號
Regex(@"^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$"); // 同上,不過這里可以限制長度

Regex(@"[^%&’,;=?$\x22]+");                 // 可以輸入含有^%&’,;=?$\"等字符
Regex(@"[^~\x22]+");                        // 禁止輸入含有~的字符

特殊需求表達式

Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");   // 驗證email地址

Regex(@"[a-zA-z]+://[^\s]*");                              // 驗證URL網址
Regex(@"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$");
Regex(@"^([a-zA-Z]+://)?([\w-\.]+)(\.[a-zA-Z0-9]+)(:\d{0,5})?/?([\w-/]*)\.?([a-zA-Z]*)\??(([\w-]*=[\w%]*&?)*)$");

Regex(@"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$");  // 驗證手機號碼

Regex(@"^($$\d{3,4}-)|\d{3.4}-)?\d{7,8}$");               // 驗證電話號碼
Regex(@"\d{3}-\d{8}|\d{4}-\d{7}");                        // 驗證國內電話號碼

Regex(@"^\d{15}|\d{18}$");                                                 // 身份證號(15位、18位數字)
Regex(@"^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$");  // 短身份證號碼(數字、字母x結尾)

//帳號是否合法(字母開頭,允許5-16字節,允許字母數字下划線)
Regex(@"^[a-zA-Z][a-zA-Z0-9_]{4,15}$");

//密碼(以字母開頭,長度在6~18之間,只能包含字母、數字和下划線)
Regex(@"^[a-zA-Z]\w{5,17}$");

//強密碼(必須包含大小寫字母和數字的組合,不能使用特殊字符,長度在8-10之間)
Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$");

//日期格式
Regex(@"^\d{4}-\d{1,2}-\d{1,2}");
//一年的12個月(01~09和1~12)
Regex(@"^(0?[1-9]|1[0-2])$");
//一個月的31天(01~09和1~31)
Regex(@"^((0?[1-9])|((1|2)[0-9])|30|31)$");


//錢的輸入格式:
//有四種錢的表示形式我們可以接受:”10000.00″ 和 “10,000.00”, 和沒有 “分” 的 “10000” 和 “10,000”
Regex(@"^[1-9][0-9]*$");

//這表示任意一個不以0開頭的數字,但是,這也意味着一個字符”0″不通過,所以我們采用下面的形式
Regex(@"^(0|[1-9][0-9]*)$");

//一個0或者一個不以0開頭的數字.我們還可以允許開頭有一個負號
Regex(@"^(0|-?[1-9][0-9]*)$");

//這表示一個0或者一個可能為負的開頭不為0的數字.讓用戶以0開頭好了.把負號的也去掉,因為錢總不能是負的吧.下面我們要加的是說明可能的小數部分
Regex(@"^[0-9]+(.[0-9]+)?$");

//必須說明的是,小數點后面至少應該有1位數,所以”10.”是不通過的,但是 “10” 和 “10.2” 是通過的
Regex(@"^[0-9]+(.[0-9]{2})?$");
//這樣我們規定小數點后面必須有兩位,如果你認為太苛刻了,可以這樣
Regex(@"^[0-9]+(.[0-9]{1,2})?$");
//這樣就允許用戶只寫一位小數。下面我們該考慮數字中的逗號了,我們可以這樣
Regex(@"^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$");
//1到3個數字,后面跟着任意個 逗號+3個數字,逗號成為可選,而不是必須
Regex(@"^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$");

//xml文件
Regex(@"^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$");
//中文字符的正則表達式
Regex(@"[\u4e00-\u9fa5]");
//雙字節字符
Regex(@"[^\x00-\xff] (包括漢字在內,可以用來計算字符串的長度(一個雙字節字符長度計2,ASCII字符計1))");
//空白行的正則表達式,可用來刪除空白行
Regex(@"\n\s*\r");
//HTML標記的正則表達式
Regex(@"<(\S*?)[^>]*>.*?</\1>|<.*? />");// (網上流傳的版本太糟糕,上面這個也僅僅能部分,對於復雜的嵌套標記依舊無能為力)
//首尾空白字符的正則表達式
Regex(@"^\s*|\s*$或(^\s*)|(\s*$)");// (可以用來刪除行首行尾的空白字符(包括空格、制表符、換頁符等等),非常有用的表達式)
//騰訊QQ號
Regex(@"[1-9][0-9]{4,}"); //(騰訊QQ號從10000開始)
//中國郵政編碼
Regex(@"[1-9]\d{5}(?!\d)");// (中國郵政編碼為6位數字)
//IP地址
Regex(@"\d+\.\d+\.\d+\.\d+");// (提取IP地址時有用)
Regex(@"((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))");

使用正則匹配: C#中字符串常量以@開頭,這樣優點是轉義序列不被處理,按“原樣”輸出

matches = 在指定的輸入字符串中搜索正則表達式的所有匹配項。
match = 在指定的輸入字符串中搜索 Regex 構造函數中指定的正則表達式的第一個匹配項。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 正則匹配的基本使用1

            string str = "Address=192.168.1.1;Name=lyshark;Host=9999";

            Regex reg = new Regex("Name=(.+);");  // 設置匹配條件
            Match match = reg.Match(str);         // 匹配

            string value = match.Groups[0].Value; // 獲取到匹配結果
            Console.WriteLine("匹配到數據: " + value);

            // 正則匹配的基本使用2
            string input = "1986 1997 2005 2009 2019 1951 1999 1950 1905 2003";
            string pattern = @"(?<=19)\d{2}\b";

            foreach(Match each in Regex.Matches(input,pattern))
            {
                Console.WriteLine("匹配到時間: " + each.Value);
            }

            Console.ReadKey();
        }
    }
}

正則替換字符: replace 在指定的輸入字符串內,使用指定的替換字符串替換與某個正則表達式模式匹配的所有字符串。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 正則替換掉指定單詞
            string line = "Address=192.168.1.10;  Name=lyshark;";
            Regex reg_line = new Regex("Name=(.+);");
            string modified = reg_line.Replace(line, "Name=admin;");
            Console.WriteLine("修改后的結果:  " + modified);

            // 正則替換掉多余空格
            string input = "Hello    World     ";
            string pattern = "\\s+";
            string replacement = " ";

            Regex reg = new Regex(pattern);
            string result = reg.Replace(input, replacement);

            Console.WriteLine("替換前:{0} 替換后:{1}", input, result);

            Console.ReadKey();
        }
    }
}

判斷字符串狀態: IsMatch 指示 Regex 構造函數中指定的正則表達式在指定的輸入字符串中是否找到了匹配項。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string RegexStr = string.Empty;
            // 匹配字符串的開始和結束是否為0-9的數字[定位字符]
            RegexStr = "^[0-9]+$";
            Console.WriteLine("判斷是否為數字: {0}", Regex.IsMatch("1234", RegexStr));

            // 匹配字符串中間是否包含數字(任意位子只要有一個數字即可)
            RegexStr = @"\d+";
            Console.WriteLine("判斷是否包含數字: {0}", Regex.IsMatch("你好123", RegexStr));

            // 匹配字符串開頭結尾,忽略大小寫
            RegexStr = @"Hello[\w\W]*";
            Console.WriteLine("匹配是否以Hello開頭: {0}", Regex.IsMatch("Hello Lyshark", RegexStr, RegexOptions.IgnoreCase));

            RegexStr = @"[\w\W*]Hello";
            Console.WriteLine("匹配是否已Hello結尾: {0}", Regex.IsMatch("Hello Lyshark", RegexStr, RegexOptions.IgnoreCase));

            Console.ReadKey();
        }
    }
}

正則分組匹配:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string RegexStr = string.Empty;

            // 匹配所行記錄數
            string TaobaoLink = "<a href=\"http://www.taobao.com\" title=\"淘寶網\" target=\"_blank\">淘寶</a>";
            RegexStr = @"<a[^>]+href=""(\S+)""[^>]+title=""([\s\S]+?)""[^>]+>(\S+)</a>";
            
            Match mat = Regex.Match(TaobaoLink, RegexStr);
            for (int i = 0; i < mat.Groups.Count; i++)
            {
                Console.WriteLine(mat.Groups[i].Value);
            }

            // 分組匹配
            string Resume = "姓名:lyshark|性別:男|出生日期:1991-12-12|手機:18264855695";
            RegexStr = @"姓名:(?<name>[\S]+)\|性別:(?<sex>[\S]{1})\|出生日期:(?<Birth>[\S]{10})\|手機:(?<phone>[\d]{11})";
            Match match = Regex.Match(Resume, RegexStr);
            Console.WriteLine("姓名:{0} 手機號: {1}", match.Groups["name"].ToString(),match.Groups["phone"].ToString());

            Console.ReadKey();
        }
    }
}

正則拆分字符串:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string SplitInputStr = "1xxxxx.2ooooo.3eeee.4kkkkkk.";
            string RegexStr = string.Empty;

            RegexStr = @"(\d)";
            Regex split_exp = new Regex(RegexStr);
            string[] str = split_exp.Split(SplitInputStr);

            foreach (string each in str)
                Console.WriteLine(each);

            Console.ReadKey();
        }
    }
}

解析圖片:

using System;
using System.Net;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient web = new WebClient();
            string html = web.DownloadString("http://meitulu.92demo.com/item/3186_3.html");

            MatchCollection mac = Regex.Matches(html, @"<img.+?(?<picSrc>http://.+?\.jpg).+?>");

           foreach(Match each in mac)
           {
               if(each.Success)
               {
                   // 獲取到網頁圖片路徑
                   Console.WriteLine(each.Groups["picSrc"].Value);
                   string src = each.Groups["picSrc"].Value;
               }
           }
            Console.ReadKey();
        }
    }
}

解析HTML標簽:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 獲得href中的值
            string RegexStr = string.Empty;

            string LinkA = "<a href=\"http://www.baidu.com\" target=\"_blank\">百度</a>";
            RegexStr = @"href=""[\S]+""";
            Match match = Regex.Match(LinkA, RegexStr);
            Console.WriteLine("獲得href中的值: {0}", match.Value);

            // 匹配標簽
            string LinkB = "<h1>hellolyshark</h1>";
            RegexStr = @"<h[^23456]>[\S]+</h[1]>";
            Console.WriteLine("h1值: {0}", Regex.Match(LinkB, RegexStr, RegexOptions.IgnoreCase).Value);



            RegexStr = @"ab\w+|ij\w{1,}";   //匹配ab和字母 或 ij和字母
            Console.WriteLine("{0}。多選結構:{1}", "abcd", Regex.Match("abcd", RegexStr).Value);
            Console.WriteLine("{0}。多選結構:{1}", "efgh", Regex.Match("efgh", RegexStr).Value);
            Console.WriteLine("{0}。多選結構:{1}", "ijk", Regex.Match("ijk", RegexStr).Value);



            RegexStr = @"張三?豐";    //?匹配前面的子表達式零次或一次。
            Console.WriteLine("{0}。可選項元素:{1}", "張三豐", Regex.Match("張三豐", RegexStr).Value);
            Console.WriteLine("{0}。可選項元素:{1}", "張豐", Regex.Match("張豐", RegexStr).Value);
            Console.WriteLine("{0}。可選項元素:{1}", "張飛", Regex.Match("張飛", RegexStr).Value);

            //匹配特殊字符
            RegexStr = @"Asp\.net";    //匹配Asp.net字符,因為.是元字符他會匹配除換行符以外的任意字符。
            Console.WriteLine("{0}。匹配Asp.net字符:{1}", "Java Asp.net SQLServer", Regex.Match("Java Asp.net", RegexStr).Value);
            Console.WriteLine("{0}。匹配Asp.net字符:{1}", "C# Java", Regex.Match("C# Java", RegexStr).Value);


            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string PageInfo = @"<hteml>
                        <div id=""div1"">
                            <a href=""http://www.baidu.con"" target=""_blank"">百度</a>
                            <a href=""http://www.taobao.con"" target=""_blank"">淘寶</a>
                            <a href=""http://www.cnblogs.com"" target=""_blank"">博客園</a>
                            <a href=""http://www.google.con"" target=""_blank"">google</a>
                        </div>
                        <div id=""div2"">
                            <a href=""/zufang/"">整租</a>
                            <a href=""/hezu/"">合租</a>
                            <a href=""/qiuzu/"">求租</a>
                            <a href=""/ershoufang/"">二手房</a>
                            <a href=""/shangpucz/"">商鋪出租</a>
                        </div>
                    </hteml>";
            string RegexStr = string.Empty;
            RegexStr = @"<a[^>]+href=""(?<href>[\S]+?)""[^>]*>(?<text>[\S]+?)</a>";
            MatchCollection mc = Regex.Matches(PageInfo, RegexStr);

            foreach (Match item in mc)
            {
                Console.WriteLine("href:{0}--->text:{1}", item.Groups["href"].ToString(), item.Groups["text"].ToString());
            }

            Console.ReadKey();
        }
    }
}

函數的調用方法

簡單的函數定義:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 定義一個方法,並提供參數傳遞
        public static int GetMax(int x, int y)
        {
            return x > y ? x : y;
        }
        // 定義一個判斷閏年的方法
        public static bool IsRun(int year)
        {
            bool ret = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
            return ret;
        }

        static void Main(string[] args)
        {
            int max = Program.GetMax(100, 200);
            Console.WriteLine("最大值: {0}", max);

            bool ret = Program.IsRun(2020);
            Console.WriteLine("閏年: {0}", ret);

            Console.ReadKey();
        }
    }
}

方法傳遞數組/字符串:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 方法傳遞數組
        public static int GetSum(int[] Array)
        {
            int sum = 0;
            for (int x = 0; x < Array.Length; x++)
                sum += Array[x];

            return sum;
        }
        // 方法傳遞字符串
        public static string IsString(string str)
        {
            return str;
        }

        static void Main(string[] args)
        {
            int[] Array = new int[] { 1, 2, 3, 4, 5 };

            int ret_sum = Program.GetSum(Array);
            Console.WriteLine("相加結果: {0}", ret_sum);

            string ret_str = Program.IsString("hello lyshark");
            Console.WriteLine("字符串: {0}", ret_str);

            Console.ReadKey();
        }
    }
}

Out 方法返回多個參數: 類似與C++中的多指針傳遞,就是說可以一次性傳出多個參數。

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

namespace ConsoleApplication1
{
    class Program
    {
        // 返回 max => 最大值 / main => 最小值
        public static void GetNum(int[] Array, out int Max, out int Min)
        {
            int max = int.MinValue;
            int min = int.MaxValue;

            for (int i = 0; i < Array.Length; i++)
            {
                if (Array[i] > max)
                    max = Array[i];

                if (Array[i] < min)
                    min = Array[i];
            }
            Max = max;
            Min = min;
        }

        static void Main(string[] args)
        {
            int[] Array = new int[] { 2,6,9,3,10 };
            int Max = 0;
            int Min = 0;

            GetNum(Array,out Max,out Min);

            Console.WriteLine("最大值: {0}", Max);
            Console.WriteLine("最小值: {0}", Min);

            Console.ReadKey();
        }
    }
}

Out 實現參數返回:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 自己實現TryParse
        public static bool MyTryParse(string Str,out int result)
        {
            result = 0;
            try
            {
                result = Convert.ToInt32(Str);
                return true;
            }
            catch
            {
                return false;
            }
        }

        static void Main(string[] args)
        {
          int number = 0;
          bool sys_ret = int.TryParse("123", out number);
          Console.WriteLine("系統轉換結果輸出: {0} 狀態: {1}", number,sys_ret);

          bool my_ret = Program.MyTryParse("456", out number);
          Console.WriteLine("My轉換結果輸出: {0} 狀態:{1}", number,my_ret);

          Console.ReadKey();
        }
    }
}

Ref 變量指針交換:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 變量交換,類似於指針傳遞
        public static void Exchange(ref int x,ref int y)
        {
            int tmp = x;
            x = y;
            y = tmp;
        }

        static void Main(string[] args)
        {
            int x = 100;
            int y = 200;
            Exchange(ref x, ref y);

            Console.Write("交換后: x = {0} y = {1}", x, y);

            Console.ReadKey();
        }
    }
}

params 傳遞可變參數:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 指定可變參數
        public static void GetName(int Number,params string[] Str)
        {
            for (int x = 0; x < Str.Length; x++)
                Console.Write(Number + "  " + Str[x] + "  ");
        }

        static void Main(string[] args)
        {
            GetName(1001,"admin", "lyshark", "guest");

            Console.ReadKey();
        }
    }
}

實現方法重載:

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

namespace ConsoleApplication1
{
    class Program
    {
        // 方法重載
        public static double Sum(double x,double y)
        {
            return x + y;
        }
        public static int Sum(int x, int y)
        {
            return x + y;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("int => {0}", Sum(10, 20));
            Console.WriteLine("double => {0}", Sum(10.5, 20.5));

            Console.ReadKey();
        }
    }
}

簡單定義函數委托: 通過給指定的函數傳遞函數,來實現一個函數計算多個結果.

using System;
using System.Linq;

namespace ConsoleApplication1
{
    // 聲明一個委托指向一個函數
    public delegate int Calculation(int x,int y);

    class Program
    {
        public static int Add(int x,int y)
        {
            return x + y;
        }
        public static int Sub(int x,int y)
        {
            return x - y;
        }

        // 定義函數
        public static int CheckSum(int x,int y, Calculation del)
        {
            int ret = del(x, y);
            return ret;
        }

        static void Main(string[] args)
        {
            int result = 0;

            result = CheckSum(100, 200, Add);
            Console.WriteLine("加法: " + result);

            result = CheckSum(100, 200, Sub);
            Console.WriteLine("減法: " + result);

            // 定義一個匿名函數完成計算
            Calculation dd = (int x, int y) => { return x + y; };
            result = dd(10, 20);
            Console.WriteLine("匿名函數計算: " + result);

            Console.ReadKey();
        }
    }
}

匿名函數與委托: 使用匿名函數,配合委托實現計算字符串的最大值與最小值.

using System;
using System.Linq;

namespace ConsoleApplication1
{
    // 聲明一個委托指向一個函數
    public delegate int DelCompare(object o1, object o2);

    class Program
    {
        public static object GetMax(object[] Array, DelCompare del)
        {
            object max = Array[0];
            for (int i = 0; i < Array.Length; i++)
            {
                //要傳一個比較的方法
                if (del(max, Array[i]) < 0)
                {
                    max = Array[i];
                }
            }
            return max;
        }


        static void Main(string[] args)
        {
            object[] obj = { "abc", "lyshark", "guest", "kfkc" };

            object result = GetMax(obj, (object x, object y) =>
            {
                string str1 = (string)x;
                string str2 = (string)y;
                return str1.Length - str2.Length;
            });
            Console.WriteLine("最長的結果: " + result);

            result = GetMax(obj, (object x, object y) =>
            {
                string str1 = (string)x;
                string str2 = (string)y;
                return str2.Length - str1.Length;
            });
            Console.WriteLine("最短的結果: " + result);

            Console.ReadKey();
        }
    }
}

泛型委托實現計算最大值: 相比於上面的普通委托而言,反省委托更加靈活,可以計算任意類型的數據.

using System;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    // 聲明一個委托指向一個函數
    public delegate int DelCompare<T>(T t1, T t2);

    class Program
    {
        public static T GetMax<T>(T[] Array, DelCompare<T> del)
        {
            T max = Array[0];
            for (int i = 0; i < Array.Length; i++)
            {
                //要傳一個比較的方法
                if (del(max, Array[i]) < 0)
                {
                    max = Array[i];
                }
            }
            return max;
        }

        public static int Compare(int x,int y)
        {
            return x - y;
        }

        static void Main(string[] args)
        {
            // 整數類型的調用
            int[] Array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int max = GetMax<int>(Array, (int x, int y) =>
            {
                return x - y;
            });
            Console.WriteLine("整數類型: " + max);

            max = GetMax<int>(Array, Compare);
            Console.WriteLine("整數類型: " + max);

            // 字符串類型的調用
            string[] obj = { "abc", "lyshark", "guest", "kfkc" };
            string str_max = GetMax<string>(obj, (string str1, string str2) =>
            {
                return str1.Length - str2.Length;
            });
            Console.WriteLine("字符串類型:" + str_max);

            Console.ReadKey();
        }
    }
}

類的相關知識

構造函數/析構函數:

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

namespace ConsoleApplication1
{

    class Person
    {
        public int Number;
        public string Name;
        private int tmp = 0;

        // 定義構造函數
        public Person(int x,string y)
        {
            this.Number = x;
            this.Name = y;
            Console.WriteLine("構造函數執行");
        }
        // 定義析構函數
        ~Person()
        {
            Console.WriteLine("析構函數執行");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person ptr = new Person(1001, "lyshark");
            Console.WriteLine("ID: {0} Name: {1}", ptr.Number, ptr.Name);

            Console.ReadKey();
        }
    }
}

對象中Get/Set方法: 該方法是用來限定用戶屬性的。

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

namespace ConsoleApplication1
{

    class Person
    {
        private int _age;
        public int age
        {
            // 當用戶輸出該屬性的值是執行Get方法
            get { return _age; }

            // 當用戶對該屬性賦值時執行Set方法
            set
            {
                // 判斷如果年齡小於0或者大於100則直接返回0
                if (value < 0 || value > 100)
                {
                    value = 0;
                }
                // 否則將用戶數據賦值給變量
                _age = value;
            }
        }
        // 定義構造函數
        public Person(int x)
        {
            this.age = x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person ptr = new Person(10);
            Console.WriteLine("正常年齡: {0}", ptr.age);

            Person ptr_err = new Person(102);
            Console.WriteLine("異常年齡: {0}", ptr_err.age);

            Console.ReadKey();
        }
    }
}

靜態方法與非靜態方法:

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

namespace ConsoleApplication1
{
    class Person
    {
        private static string _name;
        public static string Name
        {
            get { return Person._name; }
            set { Person._name = value; }
        }

        private char _gender;
        public char Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }
        public void M1()
        {
            Console.WriteLine("我是非靜態的方法");
        }
        public static void M2()
        {
            Console.WriteLine("我是一個靜態方法");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person ptr = new Person();

            // 調用非靜態方法
            ptr.M1();
            // 調用靜態方法
            Person.M2();

            Console.ReadKey();
        }
    }
}

繼承的基本使用:

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

namespace ConsoleApplication1
{
    // 定義基類
    public class Person
    {
        public string name;
        public int age;

        public Person(string _name, int _age)
        {
            this.name = _name;
            this.age = _age;
        }
        public void Display()
        {
            Console.WriteLine("姓名: {0} 年齡:{1} ", this.name, this.age);
        }
    }

    // 定義派生類
    public class Studnet: Person
    {
        public int stu;
        public Studnet(string _name,int _age,int _stu):base(_name,_age)
        {
            this.stu = _stu;
        }
        public void Display()
        {
            Console.WriteLine("Stu編號: {0} 學生姓名: {1} 年齡: {2}",this.stu,this.name,this.age);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 定義基類
            Person ptr = new Person("lyshark",22);
            ptr.Display();

            // 定義派生類
            Studnet stu = new Studnet("lyshark",22,1001);
            stu.Display();

            Console.ReadKey();
        }
    }
}

虛方法實現多態: 首先將父類函數標記為虛方法,然后子類就可以重寫父類的虛方法,實現多態。

using System;
using System.Collections;

namespace ConsoleApplication1
{
    // 定義一個人類的基類
    public class Person
    {
        public string name;
        public Person(string name)
        {
            this.name = name;
        }
        public virtual void SayHello()
        {
            Console.WriteLine("基類方法");
        }
    }
    // 定義日本人並繼承人類,重寫SayHello方法
    public class Japanese : Person
    {
        public Japanese(string name) : base(name) { }
        // 重寫父類的SayHello
        public override void SayHello()
        {
            base.SayHello();
            Console.WriteLine("日本人");
        }
    }
    // 定義中國並繼承人類,重寫SayHello方法
    public class Chinese : Person
    {
        public Chinese(string name) : base(name) { }
        // 重寫父類的SayHello
        public override void SayHello()
        {
            Console.WriteLine("中國人");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 普通的調用方式
            Japanese jap = new Japanese("蒼井空");
            jap.SayHello();

            Chinese chi = new Chinese("韓梅梅");
            chi.SayHello();

            // 直接通過循環調用
            Person[] per = { jap, chi };
            for (int x = 0; x < per.Length; x++)
                per[x].SayHello();

            Console.ReadKey();
        }
    }
}

抽象類實現多態: 當父類中的方法不知道如何實現的時候,可以考慮將父類定義為抽象類,將方法定義為抽象方法。

using System;
using System.Collections;

namespace ConsoleApplication1
{
    // 定義一個抽象類,等待讓子類重寫
    public abstract class Shape
    {
        public abstract double GetArea();
    }

    // 定義子類重寫抽象類
    public class CirCle:Shape
    {
        public double x;
        public double y;

        public CirCle(double x,double y)
        {
            this.x = x;
            this.y = y;
        }
        public override double GetArea()
        {
            return this.x * this.y;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 抽象類不可實例化,只能實例化子類
            Shape sp = new CirCle(12.5,20.8);
            double ret = sp.GetArea();
            Console.WriteLine("結果是: {0}", ret);

            Console.ReadKey();
        }
    }
}

接口實現多態: 接口不允許有訪問修飾符,方法自動設置為自動屬性。

using System;
using System.Collections;

namespace ConsoleApplication1
{
    // 定義一個接口,等待讓子類重寫
    public interface Person
    {
        void Display();
    }
    // 定義派生類,繼承於Person接口
    public class Student:Person
    {
        public void Display()
        {
            Console.WriteLine("定義學生");
        }
    }
    // 定義派生類
    public class Teacher:Person
    {
        public void Display()
        {
            Console.WriteLine("定義老師");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 調用學生方法
            Person stu = new Student();
            stu.Display();

            // 調用老師方法
            Person tea = new Teacher();
            tea.Display();

            Console.ReadKey();
        }
    }
}

並發與網絡編程

線程操作基礎:

using System;
using System.Collections;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        // 定義一個無參線程函數
        public static void My_Thread()
        {
            Console.WriteLine("線程函數已運行");
        }

        static void Main(string[] args)
        {
            string strinfo = string.Empty;

            ThreadStart childref = new ThreadStart(My_Thread);
            Thread thread = new Thread(childref);
            thread.Start();

            Console.WriteLine("線程唯一標識符: " + thread.ManagedThreadId);
            Console.WriteLine("線程名稱: " + thread.Name);
            Console.WriteLine("線程狀態: " + thread.ThreadState.ToString());
            Console.WriteLine("線程優先級: " + thread.Priority.ToString());
            Console.WriteLine("是否為后台線程: " + thread.IsBackground);

            Thread.Sleep(1000);
            thread.Join();

            Console.ReadKey();
        }
    }
}

線程傳遞參數:

using System;
using System.Collections;
using System.Threading;

namespace ConsoleApplication1
{
    public struct ThreadObj
    {
        public string name;
        public int age;

        public ThreadObj(string _name, int _age)
        {
            this.name = _name;
            this.age = _age;
        }
    }

    class Program
    {
        // 定義一個無參線程函數
        public static void My_Thread(object obj)
        {
            ThreadObj thread_path = (ThreadObj)obj;
            Console.WriteLine("姓名: {0} 年紀: {1}", thread_path.name, thread_path.age);
            Thread.Sleep(3000);
        }

        static void Main(string[] args)
        {
            for(int x=0;x<200;x++)
            {
                ThreadObj obj = new ThreadObj("admin", x);
                Thread thread = new Thread(My_Thread);
                thread.IsBackground = true;

                thread.Start(obj);
            }
            Console.ReadKey();
        }
    }
}

實現端口掃描:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // FTP, SSH, Telnet, SMTP, HTTP, POP3, RPC, SMB, SMTP, IMAP, POP3
            int[] Port = new int[] { 21, 22, 23, 25, 80, 110, 135, 445, 587, 993, 995 };

            foreach(int each in Port)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                try
                {
                    sock.Connect("192.168.1.10",each);
                    if(sock.Connected)
                    {
                        Console.WriteLine("端口開啟:" + each);
                    }
                }
                catch
                {
                    Console.WriteLine("端口關閉:" + each);
                    sock.Close();
                }
            }
        }
    }
}

多線程端口掃描:

using System;
using System.Net;
using System.Net.Sockets;

namespace TimeoutPortScan
{
    class TimeoutPortScan
    {
        private IPAddress ip;
        private readonly int[] ports = new int[] { 21, 22, 23, 25, 53, 80, 110, 118, 135, 143, 156, 161, 
            443, 445, 465, 587, 666, 990, 991, 993, 995, 1080, 1433, 1434, 1984, 2049, 2483, 2484, 3128, 
            3306, 3389, 4662, 4672, 5222, 5223, 5269, 5432, 5500, 5800, 5900, 8000, 8008, 8080 };

        public bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            try
            {
                IAsyncResult result = scanSocket.BeginConnect(remoteEndPoint, null, null);
                bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeoutMSec), false);
                if (result.IsCompleted && scanSocket.Connected)
                {
                    scanSocket.EndConnect(result);
                    return true;
                }
                else
                    return false;
            }
            finally
            {
                scanSocket.Close();
            }
        }

        static void Main(string[] args)
        {
            TimeoutPortScan ps = new TimeoutPortScan();

            for (int x = 1; x < 255;x++ )
            {
                string addr = string.Format("192.168.1.{0}", x);
                IPAddress.TryParse(addr, out ps.ip);

                for (int num = 0; num < ps.ports.Length; num++)
                {
                    if (ps.Connect(new IPEndPoint(ps.ip, ps.ports[num]), 100))
                        Console.WriteLine("IP:{0} --> 端口: {1} --> 狀態: Open", addr,ps.ports[num]);
                }
            }
        }
    }
}

異步端口掃描:

using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;

namespace AsyncPortScan
{
    class AsyncPortScan
    {
        static void Main(string[] args)
        {
            IPAddress ip;
            int startPort, endPort;
            if (GetPortRange(args, out ip, out startPort, out endPort) == true)  // 提取命令行參數
                Scan(ip, startPort, endPort);   // 端口掃描
        }

        /// 從命令行參數中提取端口
        private static bool GetPortRange(string[] args, out IPAddress ip, out int startPort, out int endPort)
        {
            ip = null;
            startPort = endPort = 0;
            // 幫助命令
            if (args.Length != 0 && (args[0] == "/?" || args[0] == "/h" || args[0] == "/help"))
            {
                Console.WriteLine("scan 192.168.1.10 100 2000");
                return false;
            }

            if (args.Length == 3)
            {
                // 解析端口號成功
                if (IPAddress.TryParse(args[0], out ip) && int.TryParse(args[1], out startPort) && int.TryParse(args[2], out endPort))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }
        /// 端口 掃描
        static void Scan(IPAddress ip, int startPort, int endPort)
        {
            Random rand = new Random((int)DateTime.Now.Ticks);
            for (int port = startPort; port < endPort; port++)
            {
                Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                //尋找一個未使用的端口進行綁定
                do
                {
                    try
                    {
                        scanSocket.Bind(new IPEndPoint(IPAddress.Any, rand.Next(65535)));
                        break;
                    }
                    catch
                    {
                        //綁定失敗
                    }
                } while (true);

                try
                {
                    scanSocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scanSocket, port });
                }
                catch
                {
                    continue;
                }
            }
        }

        /// BeginConnect的回調函數 異步Connect的結果
        static void ScanCallBack(IAsyncResult result)
        {
            // 解析 回調函數輸入 參數
            ArrayList arrList = (ArrayList)result.AsyncState;
            Socket scanSocket = (Socket)arrList[0];
            int port = (int)arrList[1];
            // 判斷端口是否開放
            if (result.IsCompleted && scanSocket.Connected)
            {
                Console.WriteLine("端口: {0,5} 狀態: Open", port);
            }
            scanSocket.Close();
        }
    }
}

獲取本機IP地址:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;


namespace ConsoleApplication1
{
    class Program
    {
        public static List<string> GetLocalAddress(string netType)
        {
            string HostName = Dns.GetHostName();
            IPAddress[] address = Dns.GetHostAddresses(HostName);
            List<string> IpList = new List<string>();

            if(netType == string.Empty)
            {
                for (int i = 0; i < address.Length; i++)
                {
                    IpList.Add(address[i].ToString());
                }
            }
            else
            {
                for (int i = 0; i < address.Length; i++)
                {
                    if (address[i].AddressFamily.ToString() == netType)
                    {
                        IpList.Add(address[i].ToString());
                    }
                }
            }
            return IpList;
        }

        static void Main(string[] args)
        {
            // 獲取IPV4地址
            List<string> ipv4 = GetLocalAddress("InterNetwork");
            foreach (string each in ipv4)
                Console.WriteLine(each);

            // 獲取IPV6地址
            List<string> ipv6 = GetLocalAddress("InterNetworkV6");
            foreach (string each in ipv6)
                Console.WriteLine(each);

            Console.ReadKey();
        }
    }
}

實現Get請求:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static string HttpGetPage(string url,string coding)
        {
            string pageHtml = string.Empty;
            try
            {
                using(WebClient MyWebClient = new WebClient())
                {
                    Encoding encode = Encoding.GetEncoding(coding);
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;
                    Byte[] pageData = MyWebClient.DownloadData(url);
                    pageHtml = encode.GetString(pageData);
                }
            }
            catch { }
            return pageHtml;
        }

        static void Main(string[] args)
        {
            var html = HttpGetPage("https://www.baidu.com","utf-8");

            Console.WriteLine(html);
            Console.ReadKey();
        }
    }
}

Post請求發送鍵值對:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        public static string HttpPost(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36";
            req.ContentType = "application/x-www-form-urlencoded";
            #region
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //獲取響應內容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        static void Main(string[] args)
        {
            string url = "http://www.baidu.com/";
            Dictionary<string, string> dic = new Dictionary<string, string> { };
            dic.Add("username","lyshark");
            HttpPost(url, dic);

            Console.ReadKey();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM