zl程序教程

您现在的位置是:首页 >  其他

当前栏目

C# 语言程序设计笔记

2023-02-18 16:46:24 时间

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();
        }
    }
}