失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 《Visual C# 语言从入门到精通》

《Visual C# 语言从入门到精通》

时间:2023-01-02 14:19:41

相关推荐

《Visual C# 语言从入门到精通》

C#(C Sharp)是一种通用、面向对象的编程语言,由微软公司开发。它在语法结构和概念上类似于C和C++,但也借鉴了Java的一些特性。C#是.NET平台的主要编程语言之一,广泛用于Windows应用程序开发、Web应用程序开发和游戏开发等领域。

C#特点有如下这些:

简单易用:C#的语法结构简洁清晰,易于学习和理解。它提供了丰富的编程特性和现代化的语言功能,如自动垃圾回收、类型推断、Lambda表达式等,使开发人员能够更高效地编写代码。

面向对象:C#是一种面向对象的编程语言,支持封装、继承和多态等面向对象的概念和技术。开发人员可以使用类、接口、继承和多态等特性来组织和管理代码,提高代码的可维护性和重用性。

强大的.NET框架:C#是.NET平台的一部分,可以与.NET框架紧密集成。通过.NET框架,开发人员可以使用丰富的类库和组件来实现各种功能,如文件操作、网络通信、数据库访问、图形界面等。

跨平台开发:随着.NET Core的发布,C#也可以用于跨平台开发。开发人员可以使用C#编写跨平台的应用程序,包括在Windows、Linux和macOS等操作系统上运行的应用程序。

强类型检查:C#是一种强类型语言,对变量和数据类型有严格的检查和限制。这有助于减少编程错误和类型相关的问题,并提高代码的可靠性和稳定性。

多线程支持:C#提供了多线程编程的支持,开发人员可以使用线程、任务和并行编程库来实现并发和异步操作,从而提高程序的性能和响应性。

基本的流程控制

标准输入输出

这段C#代码是一个简单的控制台应用程序。它包含一个Main方法作为程序的入口点。代码的功能是打印"hello world"到控制台,并读取用户输入的字符串并再次打印出来。

程序开始执行时,Console.WriteLine("hello world");语句会将字符串"hello world"打印到控制台。接下来,string Str = Console.ReadLine();语句会等待用户在控制台输入一行文本,并将用户输入的文本保存到名为Str的字符串变量中。最后,Console.WriteLine(Str);语句将变量Str的值再次打印到控制台。

通过这段代码,用户可以在控制台输入任意字符串,并查看输入的结果。

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

常用变量类型

这段C#代码是一个控制台应用程序。它声明了几个不同类型的变量,并赋予它们不同的初始值。

代码中声明的变量类型和初始值如下:

byte s_byte = 254;: 声明一个byte类型的变量s_byte,并将其初始值设为254。sbyte s_sbyte = 126;: 声明一个sbyte类型的变量s_sbyte,并将其初始值设为126。short s_short = 32766;: 声明一个short类型的变量s_short,并将其初始值设为32766。int s_int = 2147483645;: 声明一个int类型的变量s_int,并将其初始值设为2147483645。double s_double = 3.1415926;: 声明一个double类型的变量s_double,并将其初始值设为3.1415926。decimal d_decimal = 5000m;: 声明一个decimal类型的变量d_decimal,并将其初始值设为5000。string s_string = "hello lyshark";: 声明一个string类型的变量s_string,并将其初始值设为"hello lyshark"。

这些变量可以在程序的其他部分使用,进行各种操作和计算。在这段代码中,变量只是被声明和初始化,没有进一步的处理或输出。

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语句的构建

这段C#代码是一个控制台应用程序。它包含了一些常量和条件语句。

代码中定义了两个常量:

const int x = 100;: 定义一个名为x的整型常量,并将其值设置为100。const int y = 200;: 定义一个名为y的整型常量,并将其值设置为200。

然后,代码声明了一个整型变量source并将其初始值设为0。

接下来,程序会要求用户输入一个数,并将输入的值存储在source变量中,通过int.Parse()方法将输入的字符串转换为整型。

然后,程序使用条件语句对输入的值进行判断:

如果输入的值等于0,程序会输出"你没有输入任何数。"如果输入的值大于x且小于y,程序会输出"符合规范"。

最后,通过Console.ReadKey()方法等待用户按下任意键结束程序的执行。

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语句的构建

这段C#代码是一个控制台应用程序。它根据用户输入的整数分数,使用switch语句判断分数的等级。

代码首先输出提示信息,要求用户输入一个整数。

然后,使用Convert.ToInt32()方法将用户输入的字符串转换为整数,并将其存储在变量score中。

接下来,代码使用switch语句根据score / 10的值进行判断:

如果score / 10的值为10或9,程序会输出"A"。如果score / 10的值为8或7,程序会输出"B"。对于其他情况,即无法匹配到上述条件的值,程序会输出"none"。

最后,通过Console.ReadKey()方法等待用户按下任意键结束程序的执行。

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与Do-While语句的构建

这段C#代码是一个控制台应用程序。它演示了如何使用循环遍历数组并打印数组中的值。

代码首先创建了一个包含10个整数的数组MyArray

然后,使用while循环,通过递增的index变量来遍历数组。在每次循环中,使用Console.WriteLine()方法打印数组中当前索引位置的值,并在格式字符串中使用占位符{0}来引用该值。

接下来,使用do-while循环,同样通过递增的index变量遍历数组。在每次循环中,使用Console.Write()方法打印数组中当前索引位置的值,但不换行。

最后,通过Console.ReadKey()方法等待用户按下任意键结束程序的执行。这样,程序会先使用while循环打印数组的值,然后使用do-while循环在同一行上连续打印数组的值。

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语句的构建

这段C#代码演示了如何使用循环遍历数组和ArrayList,并打印它们的值。

代码首先创建了一个包含10个整数的数组MyArray

然后,使用for循环来遍历数组。在每次循环中,使用Console.WriteLine()方法打印当前索引和对应的数组元素的值。通过MyArray.Length可以获取数组的长度,从而确定循环的终止条件。

接下来,创建了一个ArrayList对象alt,并使用Add()方法向其中添加两个字符串元素。

使用foreach循环遍历alt,并通过变量Str依次获取每个元素的值。在循环中,使用Console.WriteLine()方法打印当前元素的值。

最后,通过Console.ReadKey()方法等待用户按下任意键结束程序的执行。这样,程序会先使用for循环打印数组的值,然后使用foreach循环打印ArrayList的值。

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跳出循环

这段C#代码演示了使用嵌套的for循环和break语句来控制程序流程。

代码中的外层for循环用于控制变量x的值,从0到4循环。

在每次外层循环中,内层的for循环用于控制变量y的值,从0到9循环。

在内层循环中,通过条件判断if (y == 3)来判断变量y的值是否等于3。如果满足条件,使用break语句跳出内层循环。

如果变量y的值不等于3,则使用Console.WriteLine()方法打印当前的y的值。

最后,通过Console.ReadKey()方法等待用户按下任意键结束程序的执行。

因此,程序会在外层循环的每次迭代中执行内层循环,内层循环会打印变量y的值,但当y的值为3时,内层循环会被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跳出循环

这段C#代码演示了使用数组和for循环来查找特定的字符串成员,并使用goto语句进行跳转。

代码中定义了一个包含3个字符串元素的字符串数组MyStr

使用for循环遍历数组中的每个元素,通过MyStr[x].Equals("lyshark")判断当前元素是否等于字符串"lyshark"。

如果找到匹配的元素,则使用goto语句跳转到标签Is_Found

标签Is_Found后面的代码将被执行,即打印"查找到成员"。

最后,通过Console.ReadKey()方法等待用户按下任意键结束程序的执行。

因此,程序会在数组中查找是否存在字符串"lyshark",如果找到匹配的字符串,则跳转到标签Is_Found,并打印"查找到成员"。

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

定义并使用枚举类型

这段C#代码演示了枚举类型的使用。

在代码中定义了一个枚举类型QQState,包含了5个状态:OnLine、OffLine、Leave、Busy和QMe。每个状态都被赋予一个整数值。

Main方法中,首先将枚举类型QQState的一个成员赋给变量state,然后通过将state强制转换为整数,将其值存储在变量num中,并打印num的值。

接下来,将整数值2赋给变量num1,然后通过将num1强制转换为枚举类型QQState,将其值存储在变量x中,并打印x的值。

然后,程序通过Console.ReadLine()方法获取用户输入的字符串,并使用switch语句根据输入的字符串值进行匹配。在这个示例中,只处理输入值为"1"的情况。在该情况下,使用Enum.Parse方法将输入的字符串转换为QQState枚举类型,并将转换后的枚举值存储在变量s1中,并打印s1的值。

最后,通过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();}}}

定义结构数据

这段C#代码演示了结构体(struct)的使用。

在代码中定义了一个结构体Person,它包含了两个成员变量widthheight,分别表示宽度和高度。

结构体也可以具有构造函数。在结构体Person中定义了一个带有两个参数的构造函数,用于初始化结构体的成员变量。

Main方法中,首先创建了一个名为perPerson类型的变量,并通过直接访问成员变量的方式给per赋值。

然后,创建了一个名为ptrPerson类型的变量,并使用带有两个参数的构造函数初始化ptr的成员变量。

最后,通过Console.WriteLine()方法打印了perptr的成员变量的值。

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

遍历文件目录

这段C#代码使用递归方式遍历指定目录下的所有文件和文件夹,并输出它们的完整路径。

在代码中,定义了一个名为Director的静态方法,接受一个字符串参数dir,表示目录路径。该方法使用DirectoryInfo类获取目录信息,并使用GetFileSystemInfos方法获取目录下的所有文件和文件夹。

然后,通过遍历fsinfos数组中的每个元素,判断元素是否为文件夹。如果是文件夹,则递归调用Director方法,传入文件夹的完整路径作为参数,以便继续遍历文件夹内的内容。如果是文件,则使用Console.WriteLine方法输出文件的完整路径。

Main方法中,调用Director方法,并传入一个目录路径作为参数。在这个示例中,指定的目录路径为d:\\,表示在D盘根目录下进行遍历。

最后,通过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();}}}

序列化与反序列化

这段代码用于演示结构体的序列化和反序列化过程。

在代码中,定义了一个名为Person的结构体,结构体中包含了两个字段nameage,表示人的姓名和年龄。结构体还定义了一个构造函数用于初始化字段的值。

Main方法中,首先创建了一个Person结构体对象ptr,并使用文件流(FileStream)将其序列化保存到文件中。使用BinaryFormatter进行序列化操作,将结构体对象写入文件流中。在这个示例中,使用了名为save.json的文件来保存序列化数据。

接着,通过使用文件流和BinaryFormatter进行反序列化操作,将保存的数据读取回来并赋值给另一个Person结构体对象read_ptr。最后,输出读取到的姓名(read_ptr.name)。

需要注意的是,在序列化和反序列化的过程中,使用的文件路径需要根据实际情况进行设置。在这个示例中,序列化和反序列化操作都使用了名为save.json的文件。

最后,通过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();}}}

实现文件读写

这段代码用于演示文件的读写操作。

在代码中,首先使用FileStream创建一个文件流对象fsWrite,并指定文件路径为C:\test.log。通过使用Write方法,循环写入100次字符串"你好世界 \n"到文件中。将字符串转换为字节数组,然后使用文件流将字节数组写入文件。

接着,创建一个文件流对象fsRead,并指定文件路径为C:\test.log。定义一个字节数组buffer1用于存储从文件中读取的数据。使用文件流的Read方法将文件中的数据读取到字节数组buffer1中,并返回读取的字节数。

然后,使用Encoding.UTF8.GetString方法将字节数组中的数据按照UTF-8编码格式解码成字符串,并赋值给变量s

最后,关闭文件流fsRead,释放资源,并输出读取到的字符串s

需要注意的是,在读写文件的过程中,使用的文件路径需要根据实际情况进行设置。在这个示例中,读写操作都使用了名为test.log的文件。

最后,通过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();}}}

逐行读取数据

这段代码用于演示使用StreamWriterStreamReader进行文本文件的读写操作。

首先,使用StreamWriter创建一个文本写入流对象sw,并指定文件路径为C:\test.txt。通过使用Write方法循环写入10次字符串"追加写入数据 \n"到文件中。每次写入都会追加到文件末尾,因为在创建StreamWriter对象时使用了true参数。

接着,创建一个文本读取流对象sr,并指定文件路径为C:\test.txt。使用StreamReaderReadLine方法循环读取文件的每一行,并将读取到的字符串赋值给变量str。然后,将读取到的字符串打印到控制台。

需要注意的是,在读写文件的过程中,使用的文件路径需要根据实际情况进行设置。在这个示例中,读写操作都使用了名为test.txt的文本文件。

最后,通过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();}}}

实现文件拷贝

这段代码用于复制文件。演示了如何使用FileStream复制文件的操作。

首先,定义了一个名为CopyFile的方法,接受源文件路径soucre和目标文件路径target作为参数。在该方法中,使用FileStream创建一个读取流对象fsRead,打开源文件并以只读方式访问。接着,使用FileStream创建一个写入流对象fsWrite,打开目标文件并以打开或创建方式进行写入。

接下来,使用一个循环来读取源文件的内容,并将读取到的数据写入到目标文件中。循环中,使用Read方法从读取流中读取数据,并将读取到的字节数保存在变量r中。如果读取到的字节数为0,表示已经读取完毕,退出循环。否则,使用Write方法将读取到的数据写入写入流中。

最后,在Main方法中,定义源文件路径为c:\save.json,目标文件路径为c:\cpy.json。然后,调用CopyFile方法,将源文件复制到目标文件。

需要注意的是,在执行文件复制操作时,需要确保源文件存在并且目标文件的路径是可写的。在这个示例中,源文件路径为c:\save.json,目标文件路径为c:\cpy.json

最后,通过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();}}}

文件路径获取

这段代码演示了使用System.IO.Path类来操作文件路径的一些常用方法。使用Path类来操作文件路径,包括获取文件名、文件扩展名、文件所在文件夹的名称等常用操作。

Main方法中,定义了一个字符串变量str,表示一个文件路径C:\save.json

以下是代码中使用的Path类的方法解释:

Path.GetFileName(str):获取文件名,输出为save.jsonPath.GetFileNameWithoutExtension(str):获取不包含扩展名的文件名,输出为savePath.GetExtension(str):获取文件的扩展名,输出为.jsonPath.GetDirectoryName(str):获取文件所在的文件夹的名称,输出为C:\Path.GetFullPath(str):获取文件所在的全路径,输出为C:\save.jsonbine(@"c:\a\", "b.txt"):连接两个字符串作为路径,输出为c:\a\b.txt

接下来,代码使用LastIndexOfSubstring方法来截取文件名部分。首先,使用LastIndexOf方法获取最后一个反斜杠\的索引位置,然后使用Substring方法截取索引位置之后的部分,得到文件名save.json

最后,通过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(bine(@"c:\a\", "b.txt"));int index = str.LastIndexOf("\\");str = str.Substring(index + 1);Console.WriteLine(str);Console.ReadKey();}}}

创建删除文件

这段代码演示了使用System.IO.File类来创建、删除、复制和剪切文件。请注意,执行这些文件操作可能需要适当的权限。

Main方法中,代码按顺序执行以下操作:

File.Create(@"C:\test.log"):创建一个名为test.log的文件,并保存在C:\目录下。输出"创建成功",并等待用户按下任意键。File.Delete(@"C:\test.log"):删除C:\test.log文件。输出"删除成功",并等待用户按下任意键。File.Copy(@"C:\test.log", @"C:\new.txt"):复制C:\test.log文件到C:\new.txt。输出"复制成功",并等待用户按下任意键。File.Move(@"C:\test.log", @"C:\new.txt"):将C:\test.log文件剪切/重命名为C:\new.txt。输出"剪切成功",并等待用户按下任意键。

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

二进制文件存取

这段代码演示了使用File.WriteAllBytes方法将字符串转换为字节数组并写入文本文件,以及使用File.ReadAllBytes方法从文本文件中读取字节数组并将其转换为字符串。

如何使用File.WriteAllBytesFile.ReadAllBytes方法进行字节级的文件读写操作,并使用适当的编码将字节数组转换为字符串和字符串转换为字节数组。在这个例子中,使用了默认的编码方式进行转换,但你也可以根据需要选择其他编码方式。请注意,执行这些文件操作可能需要适当的权限。

Main方法中,代码按顺序执行以下操作:

定义字符串s,其中包含一段文本。使用Encoding.Default.GetBytes(s)将字符串s转换为字节数组buffer。使用File.WriteAllBytes(@"C:\1.txt", buffer)将字节数组buffer以字节形式写入到文件C:\1.txt中。使用File.ReadAllBytes(@"C:\1.txt")读取文件C:\1.txt中的字节数组到read_buf。使用Encoding.Default.GetString(read_buf)将字节数组read_buf转换为字符串read_str。输出字符串read_str,即从文件中读取的文本内容。等待用户按下任意键。

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类中的各种方法对数组进行各种操作。

System.Array类是在C#中用于处理数组的基类。它是所有数组类型的基类,包括静态数组和动态数组(例如List<T>)。System.Array提供了许多有用的方法和属性,用于操作和管理数组。以下是一些常用的System.Array类成员:

Length属性:获取数组的总元素数。Rank属性:获取数组的维度数。GetLength(int dimension)方法:获取指定维度的元素数。GetLowerBound(int dimension)方法:获取指定维度的最小索引值。GetUpperBound(int dimension)方法:获取指定维度的最大索引值。GetValue(params int[] indices)方法:获取指定索引处的数组元素的值。SetValue(object value, params int[] indices)方法:设置指定索引处的数组元素的值。Clone()方法:创建当前数组的浅表副本。CopyTo(Array array, int index)方法:将当前数组的元素复制到另一个数组中。IndexOf(object value)方法:在数组中搜索指定的元素,并返回其第一个匹配项的索引。Sort()方法:对数组的元素进行排序。

通过使用System.Array类的这些成员,可以轻松地执行各种操作,例如获取数组的大小、访问特定元素、复制数组、搜索元素以及对数组进行排序等。

数组可以是静态数组或动态数组(也称为列表)。让我们更详细地了解它们吧。

静态数组:静态数组是在编译时定义并具有固定长度的数组。它们使用固定的内存块来存储数据,并且在创建后大小不能更改。声明静态数组时,需要指定元素的类型和数组的大小。

静态数组在创建后无法动态调整大小,如果需要添加或删除元素,就需要创建一个新的数组,并将旧数组的值复制到新数组中。

动态数组(列表):动态数组是在运行时创建并可以根据需要调整大小的数组。在C#中,System.Collections.Generic命名空间提供了List<T>类,它是一个动态数组的实现。与静态数组不同,动态数组可以动态地添加、删除和调整大小,无需创建新的数组。

动态数组(列表)相对于静态数组具有更多的灵活性和便利性,因为它们可以根据需要动态调整大小,并且提供了一组方便的方法来操作数组元素。然而,静态数组在某些情况下可能更加高效,因为它们在内存上是连续的,并且不需要额外的引用对象。因此,在选择使用静态数组还是动态数组时,需要根据具体需求和性能考虑做出决策。

一维数组

这是一个使用System.Array类的简单示例。在这个示例中,我们创建了一个一维整数数组IntArray和一个一维字符串数组StrArray。然后,我们为数组分配了相应的大小,并为其中的元素赋值。

IntArray是一个包含10个元素的整数数组,初始化为1到10的连续数字。StrArray是一个包含3个元素的字符串数组,通过索引赋值为字符串"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};// 定义一维字符串数组string[] StrArray = new string[3];StrArray[0] = "abc" ;StrArray[1] = "abc";Console.ReadKey();}}}

上述示例中未使用System.Array类的其他方法或属性。这只是一个简单的示例,展示了如何创建和初始化数组。根据需要,您可以使用System.Array类的其他成员来操作和管理数组。

删除元素(一维数组)

在示例中,我们扩展了之前的代码,添加了对数组的遍历和删除操作。

首先,我们使用foreach循环遍历IntArray数组中的每个元素,并使用Console.WriteLine方法将其打印到控制台上。

然后,我们定义了一个变量Del_Num,它表示要删除的元素的索引。在这个示例中,我们删除数组中的第三个元素,即索引为2的元素。

接下来,我们使用for循环从Del_Num开始迭代数组的剩余部分。在每次迭代中,我们将当前元素的值设为前一个元素的值,实现了删除指定元素的效果。

最后,我们调用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();}}}

请注意,这个示例只是展示了如何遍历数组并删除指定元素的一种方式。在实际应用中,可能需要考虑更多的边界条件和逻辑。此外,C#还提供了更多的集合类型和方法,可以更方便地操作和管理数据集合。

寻找最大最小值

这个示例展示了如何在一维数组中查找最大值、最小值、总和以及平均值。

首先,我们定义了一个一维数组Array,其中包含了一些整数。

然后,我们声明了三个变量minmaxsum,分别用于存储最小值、最大值和总和。我们将min初始化为int.MaxValue,将max初始化为int.MinValue,将sum初始化为0。

接下来,我们使用for循环遍历数组的每个元素。在循环中,我们比较当前元素与maxmin的值,并更新它们。同时,我们将当前元素的值累加到sum中。

最后,我们通过除以数组的长度来计算平均值,并使用Console.WriteLine方法打印出最大值、最小值、总和和平均值。

最后,我们调用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();}}}

数组组合为字符串

这个示例展示了如何将字符串数组中的元素连接成一个字符串,并在每个元素之间添加分隔符。

首先,我们定义了一个字符串数组name,其中包含一些名称。

然后,我们声明一个空字符串str,用于存储连接后的结果。

接下来,我们使用for循环遍历数组中的元素,从索引0到倒数第二个元素。在循环中,我们将当前元素与分隔符"|"连接,并将结果追加到str中。

最后,我们将最后一个元素直接追加到str中,而不添加分隔符。

最后,我们使用Console.WriteLine方法打印出最终的连接结果str + name[name.Length - 1]

注意,这里使用了字符串连接操作符"+",但在实际应用中,特别是在处理大量字符串时,推荐使用StringBuilder类来提高性能和效率。

最后,我们调用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();}}}

数组元素反转

这个示例展示了如何反转字符串数组中的元素顺序。

首先,我们定义了一个字符串数组name,其中包含一些名称。

然后,我们声明一个临时变量tmp,用于交换元素。

接下来,我们使用两个for循环来进行元素交换。第一个循环从数组的开头到数组长度的一半,对称地交换元素位置。在循环中,我们首先将最后一个元素赋值给tmp,然后将数组开头的元素赋值给最后一个元素,最后将tmp的值赋给数组开头的元素,完成两个元素的交换。这样,数组中的元素顺序被逆序。

最后,我们使用一个for循环遍历数组(除了最后一个元素),并使用Console.Write方法打印每个元素和一个分隔符" |"。注意,这里使用Console.Write而不是Console.WriteLine,以便在同一行上打印所有元素。

最后,我们调用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();}}}

实现冒泡排序

这个示例展示了如何使用冒泡排序算法对整数数组进行排序,并使用自定义的排序函数和.NET Framework提供的排序方法来实现。

在这个示例中,我们首先定义了一个静态方法Sort,它接受一个整数数组作为参数,并使用冒泡排序算法对数组进行排序。冒泡排序算法通过多次遍历数组,比较相邻的元素并交换它们的位置,将较大的元素逐步"浮"到数组的末尾,从而实现排序。在每一轮遍历中,最大的元素都会"冒泡"到合适的位置。

然后,我们定义了另一个静态方法Display,它接受一个整数数组作为参数,并在控制台上打印数组的内容。

Main方法中,我们创建了一个包含一些整数的数组MyArray。首先,我们调用自定义的Sort方法对数组进行排序,并使用Display方法打印排序后的结果。然后,我们使用.NET Framework提供的Array.Sort方法对数组进行排序,这是一种更快速和高效的排序方法。最后,我们使用Array.Reverse方法对数组进行反向排序,将数组的元素顺序颠倒过来。

在最后,我们调用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 合并成 Array3int 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];elseArray3[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 = 二维数组中的2for (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){// 动态创建 ArrayListArrayList 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);elsex--;}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 = valuehash.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]]++;// 这个字符在集合当中是第一次出现elsedict[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不相等返回-1Console.WriteLine("Str1 比较 Str2 " + pare(Str1, Str2));Console.WriteLine("Str1 比较 Str3 " + pare(Str1, Str3));// Compare To 比较字符串Console.WriteLine("Str1 比较 Str2 " + pareTo(Str2));Console.WriteLine("Str1 比较 Str3 " + pareTo(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 = "-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 -> ollehchar[] 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 hellostring 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@";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 = puteHash(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){// 正则匹配的基本使用1string 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);// 正则匹配的基本使用2string input = "1986 1997 1951 1999 1950 1905 ";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=\"\" 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 ;using System.Text.RegularExpressions;namespace ConsoleApplication1{class Program{static void Main(string[] args){WebClient web = new WebClient();string html = web.DownloadString("/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=\"\" 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"; //匹配字符,因为.是元字符他会匹配除换行符以外的任意字符。Console.WriteLine("{0}。匹配字符:{1}", "Java SQLServer", Regex.Match("Java ", RegexStr).Value);Console.WriteLine("{0}。匹配字符:{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="""" 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();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{// 自己实现TryParsepublic 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则直接返回0if (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) { }// 重写父类的SayHellopublic override void SayHello(){base.SayHello();Console.WriteLine("日本人");}}// 定义中国并继承人类,重写SayHello方法public class Chinese : Person{public Chinese(string name) : base(name) { }// 重写父类的SayHellopublic override void SayHello(){Console.WriteLine("中国人");}}class Program{static void Main(string[] args){// 普通的调用方式Japanese jap = new Japanese("test1");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 ;using .Sockets;namespace ConsoleApplication1{class Program{static void Main(string[] args){// FTP, SSH, Telnet, SMTP, HTTP, POP3, RPC, SMB, SMTP, IMAP, POP3int[] 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 ;using .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;}elsereturn 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 ;using .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;elsereturn 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 ;using workInformation;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 ;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("","utf-8");Console.WriteLine(html);Console.ReadKey();}}}

Post请求发送键值对:

using System;using System.Collections.Generic;using System.Linq;using ;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";#regionStringBuilder 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();}#endregionHttpWebResponse 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 = "/";Dictionary<string, string> dic = new Dictionary<string, string> { };dic.Add("username","lyshark");HttpPost(url, dic);Console.ReadKey();}}}

如果觉得《《Visual C# 语言从入门到精通》》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。