C#笔记

入门

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test{
class Program{
static void Main(string[] args){
string s=string.Empty;
Console.Title="Title"; //控制台标题
Console.WriteLine("Hello World!");
s=Console.ReadLine();
}
}
}

Char类常用方法

IsDigit IsLetter IsLetterOrDigit IsLower IsNumber IsPunctuation IsSeparator IsUpper IsWhiteSpace Parse ToLower ToString ToUpper TryParse

多级转义

1
Console.WriteLine(@"..."); //不需要转义字符进行转义

动态常量

1
2
3
4
5
6
7
class Program{
readonly int Price;
Programe(){
Price=368;
}
static void Main(string[] args){}
}

Convert类常用方法

ToBoolean ToByte ToChar ToDateTime ToDecimal ToDouble ToInt32 ToInt64 ToSByte ToSingle ToString ToUInt32 ToUInt64

数组

一维数组

1
2
3
4
int[] arr=new int[5];
for(int i=0;i<arr.Length;i++){
arr[i]=i+1;
}

二维数组

以下两种方法均可。

1
2
3
4
5
int[,] a=new int[2,4];

int[][] a=new int[2][];
a[0]=new int[2];
a[1]=new int[3];

foreach

1
2
3
4
string[] roles={"a","b",...};
foreach(string role in roles){
Console.WriteLine(role+" ");
}

List

1
2
List<string> list=new List<string>();
list.Add("...");

Sort

从小到大,只能为一维数组。

1
2
3
4
5
6
7
8
9
public static void Sort(Array array)
public static void Sort(Array array,int index,int length)
/*
index:排序范围内的起始索引
length:排序范围内的元素数
*/

int[] arr=new int[]{3,9,27,6,18,12,21,15};
Array.Sort(arr);

Reverse

用法同上。

字符串

IndexOf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public int IndexOf(char value)
public int IndexOf(string value)
public int IndexOf(char value,int startIndex)
public int IndexOf(string value,int startIndex)
public int IndexOf(char value,int startIndex,int count)
public int IndexOf(string value,int startIndex,int count)
/*
value:要检索的字符或字符串
startindex:搜索起始位置
count:要检查的字符位置数
*/

string str="We are the world";
int size=str.IndexOf('e'); //1

string str="We are the world";
int firstIndex=str.IndexOf("r");
int secondIndex=str.IndexOf("r",firstIndex+1);
int thirdIndex=str.IndexOf("r",secondIndex+1);

LastIndexOf

用法同上。

StartsWith

1
2
3
4
5
6
7
8
9
10
public bool StartsWith(string value)
public bool StartsWith(string value,bool ignoreCase,CultureInfo culture)
/*
value:要比较的字符串
ignoreCase:忽略大小写为true,否则false
culture:确定如何对字符串与value进行比较的区域性信息
*/

string str="Keep on ...";
bool result=str.StartsWith("keep",true,null);

Equals

1
2
3
4
5
6
7
public bool Equals(string value)
public static bool Equals(string a,string b)

string pwd=Console.ReadLine();
if(pwd.Equals("aaa")){
//...
}

ToUpper/ToLower

1
2
Console.WriteLine(str.ToUpper());
Console.WriteLine(str.ToLower());

Format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Console.WriteLine(string.Format("aaa{0:D}",1234));//1234
Console.WriteLine(string.Format("aaa{0:C}",5201));//货币形式 不包括小数 0表示第1个参数 ¥5,201.00
Console.WriteLine(string.Format("aaa{0:E}",120000.1));//科学计数法 1.200001E+005
Console.WriteLine(string.Format("aaa{0:N0}",12800));//分隔符显示 第2个0表示保留0位小数点 12,800
Console.WriteLine(string.Format("aaa{0:F2}",Math.PI));//小数点后2位 3.14
Console.WriteLine(string.Format("aaa{0:X4}",33));//16进制 0021
Console.WriteLine(string.Format("aaa{0:P0}",0.01))//百分号 1%
int money=1298;
Console.WriteLine(money.ToString("C"));

DateTime strDate=DateTime.Now;
Console.WriteLine(string.Format("{0:d}",strDate));//短日期
Console.WriteLine(string.Format("{0:D}",strDate));//长日期
Console.WriteLine(string.Format("{0:f}",strDate));//长日期短时间
Console.WriteLine(string.Format("{0:F}",strDate));//长日期长时间
Console.WriteLine(string.Format("{0:g}",strDate));//短日期短时间
Console.WriteLine(string.Format("{0:G}",strDate));//短日期短时间
Console.WriteLine(string.Format("{0:M}",strDate));//月日 或m
Console.WriteLine(string.Format("{0:t}",strDate));//短时间
Console.WriteLine(string.Format("{0:T}",strDate));//长时间
Console.WriteLine(string.Format("{0:Y}",strDate));//年月 或y
DateTime dTime=DateTime.Now;
Console.WriteLine(dTime.ToString("Y"));

Substring

1
2
3
4
5
6
public string Substring(int startIndex);
public string Substring(int stratIndex,int length);

string strFile="Program.cs";
string strFileName=strFile.Substring(0,strFile.IndexOf('.'));
string strExtension=strFile.Substring(strFile.IndexOf('.'));

Split

1
2
3
4
5
char[] separator={','};
string[] splitStrings=str.Split(separator,StringSplitOptions.RemoveEmptyEntries);
for(i=0;i<splitStirng.Length;i++){
Console.WriteLine(splitStirng[i]);
}

Trim

1
string shortStr=str.Trim();

Replace

1
2
3
string strOld="...";
string strNew1=strOld.Replace(',','*');
string strNew2=strOld.Replace("one","One");

StringBuilder

1
2
3
4
5
6
7
8
StringBuilder SBuilder=new StringBuilder("...");
int Num=368;
SBuilder.Append("...");//追加
SBuilder.AppendFormat("{0:C0}",Num);
SBuilder.Insert(0,"...");//开头追加
SBuilder.Remove(14,SBuilder.Length-14);//删除索引14以后的字符串
SBuilder.Replace("...","...");
Console.WriteLine(SBuilder);

OOP

类的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Program{
private int age;
public int Age{
get{
return age;
}
set{
if(value>0&&value<70)
age=value;
else
Console.WriteLine("非法");
}
}
public string FullName{ //使用自动实现属性
get;set;
}
static void Main(string[] args){
Program p=new Program();
while(true)
p.Age=Convert.ToInt16(Console.ReadLine());
}
}

构造/析构函数

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Program{
static Program(){//只能访问静态变量
Console.WriteLine("a");
}
private Program(){
Console.WriteLine("b");
}
static void Main(string[] args){
Program p1=new Program(); //调用静态构造函数 只调用一次
Program p2=new Program(); //调用第二个构造函数
}
~Program(){}
}

方法参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Program{
private int Add(int x,int y){
x=x+y;
return x;
}
private int Add(ref int x,int y){
x=x+y;
return x;
}
private int Add(int x,int y,out int z){
z=x+y;
return z;
}
private int Add(params int[] x){
int result=0;
for(int i=0;i<x.Length;i++)
result+=x[i];
return result;
}
static void Main(string[] args){
Program pro=new Program();
int x=30,y=40,z;
Console.WriteLine(pro.Add(x,y)); //x y不改变
Console.WriteLine(pro.Add(ref x,y)); //x被改变为70
Console.WriteLine(pro.Add(x,y,out z)); //z的值被改变 与ref不同 z可以定义后没有赋初始值
Console.WriteLine(pro.Add(20,30,40,50,60)); //多个参数打包为数组
return;
}
}

继承/重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Computer{
public string sayHello(){
return "a";
}
}
class Pad:Computer{ //Pad继承于Computer 不支持多类继承
public new string sayHello(){
return base.sayHello()+"b"; //调用基类方法
}
}
class Program{
static void Main(string[] args){
//两者sayHello不同
Computer pc=new Computer();
Pad ipad=new Pad();
}
}

虚方法及其重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Vehicle{
string name;
private int value;
public string Name{
get{return name;}
set{name=value;}
}
public virtual void Move(){
Console.WriteLine("{0}a",Name);
}
}
class Train:Vehicle{
public override void Move(){
Console.WriteLine("{0}b",Name);
}
}
class Car:Vehicle{
public override void Move(){
Console.WriteLine("{0}c",Name);
}
}
class Program{
static void Main(string[] args){
Vehicle vehicle=new Vehicle();
Train train=new Train();
Car car=new Car();
vehicle[] vehicles={vehicle,train,car};
vehicle.Name="1";
train.Name="2";
car.Name="3";
vehicle[0].Move(); //1a
vehicle[1].Move(); //2b
vehicle[2].Move(); //3c
return;
}
}

抽象/接口

1
2
3
4
5
6
7
8
9
10
public abstract class Market{
public string Name{get;set;}
public string Goods{get;set;}
public abstract void Shop();
}
interface Information{
string Code{get;set;}
string Name{get;set;}
void ShowInfo();
}
比较项 抽象类 接口
方法 可以有非抽象方法 所有方法都是抽象方法
属性 属性中可以有非静态变量 所有属性都是静态变量
构造函数 有构造函数 没有构造函数
继承 一个类只能继承一个父类 一个类可以同时实现多个接口
被继承 一个类可以被多个子类继承 一个接口可以同时继承多个接口

Windows控件

窗体

1
2
3
4
5
Application.Run(new Form1()); //启动窗体

Form2 frm2=new Form2();
frm2.Show();
this.Hide();

MDI窗体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Form2 frm2=new Form2();
frm2.MdiParent=this;
frm2.Show();
Form3 frm3=new Form3();
frm3.MdiParent=this;
frm3.Show();
LayoutMdi(MdiLayout.TileHorizontal); //水平平铺
LayoutMdi(MdiLayout.TileVertical); //垂直平铺
LayoutMdi(MdiLayout.Cascade); //层叠排列

//FormChild实现不重复打开同一个子窗体
FormChild formChild=new ForChild();
bool isOpened=false;
foreach(Form form in this.MdiChildren){ //循环所有已打开的子窗口
if(formChild.Name==form.Name){ //如果已经打开
formChild.Activate(); //激活该子窗口
formChild.StartPosition=FormStartPosition.CenterParent;
formChild.WindowState=FormWindowState.Normal;
isOpened=true;
formChild.Dispose(); //销毁FormChild实例 以防被再次遍历到
break;
}
}
if(!isOpened){ //没打开
formChild.MdiParent=this;
formChild.Show();
}

Label

1
2
label1.Text="...";
label1.Visible=true;

TextBox

1
2
3
4
textBox1.ReadOnly=true;
textBox1.PasswordChar='*';
textBox1.Multiline=true;
label1.Text=textBox1.Text;

RadioButton

1
2
3
4
5
radioButton1_CheckedChanged(...)

if(radioButton1.Checked){
//...
}

CheckBox

1
2
3
4
5
6
7
8
9
10
string strPop="";
foreach(Control ctrl in this.Controls){
if(ctrl.GetType().Name=='CheckBox'){
CheckBox cBox=(CheckBox)ctrl;
if(cBox.Checked){
strPop+="\n"+cBox.Text;
}
}
}
MessageBox.Show(strPop);

RichTextBox

1
2
3
4
5
6
7
8
9
10
11
12
richTextBox1.Multiline=true; //多行显示
richTextBox1.ScrollBar=RichTextBoxScrollBars.Vertical; //其他:Both None Horizontal Vertical ForcedHorizontal ForcedVertical ForcedBoth
richTextBox1.SelectionFont=new Font("楷体",12,FontStyle.Bold);
richTextBox1.SelectionColor=System.Drawing.Color.Red;
richTextBox1.SelectionBullet=true; //添加项目列表符号

private void Form1_Load(object sender,EventArgs e){
richTextBox1.Text="http://www.baidu.com";
}
private void richTextbox1_LinkClicked(object sender,LinkClickedEventArgs e){
System.Diagnostics.Process.Start(e.LinkText);
}

ComboBox

1
2
3
4
5
6
7
8
9
10
private void Form1_Load(object sender,EventArgs e){
combox1.DropDownStyle=ComboBoxStyle.DropDownList; //下拉且不能直接编辑 其他选项: Simple列表部分总可见 DropDown下拉可直接编辑
string[] str=new string[]{"a","b","c","d","e","f"};
comboBox1.DataSource=str;
comboBox1.SelectedIndex=0;
return;
}
private void comboBox1_SelectedIndexChanged(object sender,EventArgs e){
label2.Text=comboBox1.SelectedItem;
}

ListBox

1
2
3
4
5
listBox1.Items.Add("aaa");
listBox1.Items.Remove("aaa");
listBox1.HorizontalScrollbar=true;
listBox1.ScrollAlwaysVisible=true;
listBox1.SelectionMode=SelectionMode.MultiExtended; //可选用Shift/Ctrl+方向键选择多项 其他:MultiSimple可选多项 None无法选择 One只选一项

GroupBox

1
groupBox1.Text="aaa"; //设置控件标题

ListView

1
2
3
4
5
6
7
8
9
10
11
12
13
listView1.Items.Add("aaa");
listView1.Items.RemoveAt(listView1.SelectedItems[0].Index); //移除选中项
listView1.Items.Clear();
listView1.Items[2].Selected=true;
listView1.LargeImageList=imageList1; //imageList1为一个ImageList控件
listView1.SmallImageList=imageList1;
listView1.Items[0].ImageIndex=0; //第一项图标索引为imageList1中第0个
listView1.Items[1].ImageIndex=1;

listView1.Groups.Add(new ListViewGroup("aaa",_HorizontalAlignment.Left));
listView1.Groups.RemoveAt(1);
listView1.Groups.Clear();
listView1.Items[0].Group=listView1.Groups[0]; //第一项分配到第一组中

TreeView/ContextMenuStrip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private void Form1_Load(object sender,EventArgs e){
treeView1.ContextMenuStrip=contextMenuStrip1; //contextMenuStip1是个ContextMenuStrip控件 设置右键快捷菜单
TreeNode TopNode=treeView1.Nodes.Add("a"); //顶级节点
TreeNode ParentNode1=new TreeNode("b"); //基础节点
TopNode.Nodes.Add(ParentNode1);
TreeNode ChildNode1=new TreeNode("c"); //子节点
ParentNode1.Nodes.Add(ChildNode1);
imageList1.Images.Add(Image.FromFile("1.png"));
imageList1.Images.Add(Image.FromFile("2.png"));
treeView1.ImageList=imageList1;
imageList1.ImageSize=new Size(16,16);
treeView1.ImageIndex=0;
treeView1.SelectedImageIndex=1;
return;
}
private void treeView1_AfterSelect(object sender,TreeViewEventArgs e){
label1.Text=e.Node.Text;
}
private void 全部展开ToolStripMenuItem_Click(object sender,EventArgs e){
treeView1.ExpandAll();
}
private void 全部折叠ToolStripMenuItem_Click(object sender,EventArgs e){
treeView1.CollapseAll();
}

Timer

1
2
3
4
5
6
7
8
9
10
11
if(timer1.Enabled){ //是否正在运行
//...
}
timer1.Interval=1; //间隔1ms
timer1.Start(); //启动计时器
timer1.Stop(); //停止计时器
private void timer1_Tick(object sender,EventArgs e){ //触发一次
Random rnd=new Random();
label1.Text=rnd.Next(1,33).ToString("00");
return;
}

MessageBox

1
DialogResult ret=MessageBox.Show("aaa","bbb",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);

MessageBoxButtons枚举值:MessageBoxButtons.OK MessageBoxButtons.OKCancel MessageBoxButtons.AbortRetryIgnore MessageBoxButtons.YesNoCancel MessageBoxButtons.YesNo MessageBoxButtons.RetryCancel

MessageBoxIcon枚举值:MessageBoxIcon.None MessageBoxIcon.Question MessageBoxIcon.Exclaimation MessageBoxIcon.Asterisk MessageBoxIcon.Stop MessageBoxIcon.Error MessageBoxIcon.Warning MessageBoxIcon.Information

DialogResult枚举值:DialogResult.None DialogResult.OK DialogResult.Cancel DialogResult.Abort DialogResult.Retry DialogResult.Ignore DialogResult.Yes DialogResult.No

OpenFileDialog

1
2
3
4
openFileDialog1.InitialDirectory="C:\\";//初始目录
openFileDialog1.Filter="bmp文件(*.bmp)|*.bmp|gir文件(*.gif)|*.gif";//文件名筛选器
openFileDialog1.ShowDialog();
string strName=openFileDialog1.Filename;
其他属性 描述
AddExtension 用户省略扩展名时是否在文件名中添加扩展名。
DefaultExt 默认文件扩展名。
FileNames 获取所有选定文件的文件名。
Multiselect 是否允许选择多个文件。
RestoreDirectory 对话框关闭前是否还原当前目录。
其他方法 描述
OpenFile 以只读模式打开选择的文件。

SaveFileDialog

同上。

FolderBrowserDialog

1
2
3
4
folderBrowserDialog1.ShowNewFolderButton=false;//不显示新建文件夹按钮
if(folderBrowserDialog1.ShowDialog()==DialogResult.OK){
textBox1.Text=folderBrowserDialog1.SelectedPath;
}
其他属性 说明
Description 显示的说明文本。
RootFolder 开始浏览的根文件夹。

I/O

1
using System.IO;

File

Exists

确定指定的文件是否存在。权限不够也返回false。

1
bool ret=File.Exists("C:\\Test.txt");

Create

创建文件。

1
File.Create("C:\\Test.txt");

Copy

1
File.Copy("C:\\Test.txt","D:\\Test.txt");

Move

1
File.Move("C:\\Test.txt","D:\\Test.txt");

Delete

1
File.Delete("C:\\Test.txt");

FileInfo

Exists

1
2
3
4
FileInfo finfo=new FileInfo("C:\\Test.txt");
if(finfo.Exists){
//...
}

Create

1
2
FileInfo finfo=new FileInfo("C:\\Test.txt");
finfo.Create();

CopyTo

1
2
FileInfo finfo=new FileInfo("C:\\Test.txt");
finfo.CopyTo("D:\\Test.txt",true);//true表示存在则改写

MoveTo

1
2
FileInfo finfo=new FileInfo("C:\\Test.txt");
finfo.MoveTo("D:\\Test.txt");

Delete

1
2
FileInfo finfo=new FileInfo("C:\\Test.txt");
finfo.Delete();

详细信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void button1_Click(object sender,EventArgs e){
if(openFileDialog1.ShowDialog()==DialogResult.OK){
textBox1.Text=openFileDialog1.Filename;
FileInfo finfo=new FileInfo(textBox1.Text);
string strCTime=finfo.CreateionTime.ToShortDateString();
string strLATime=finfo.LastAccessTime.ToShortDateString();
string strLWTime=finfo.LastWriteTime.ToShortDateString();
string strName=finfo.Name;
string strFName=finfo.FullName;
string strDName=finfo.DirectoryName;
string strISRead=finfo.IsReadOnly.ToString();
long lgLength=finfo.Length;
}
}

Directory

Exists

1
Directory.Exists("C:\\Test");

CreateDirectory

1
DirectoryInfo.CreateDirectory("C:\\Test")

Move

只能在同一盘根目录下。

1
Directory.Move("C:\\Test","C:\\aaa\\Test");

Delete

1
Directory.Delete("C:\\Test");

DirectoryInfo

Exists

1
2
3
4
DirectoryInfo dinfo=new DirectoryInfo("C:\\Test");
if(dinfo.Exists){
//...
}

CreateDirectory

1
2
DirectoryInfo dinfo=new DirectoryInfo("C:\\Test");
dinfo.Create();

MoveTo

只能在同一盘根目录下。

1
2
DirectoryInfo dinfo=new DirectoryInfo("C:\\Test");
dinfo.MoveTo("C:\\aaa\\Test");

Delete

1
2
DirectoryInfo dinfo=new DirectoryInfo("C:\\Test");
dinfo.Delete();

FileSystemInfo

1
2
3
4
5
6
7
8
9
10
11
12
DirectoryInfo dinfo=new DirectoryInfo("...");
FileSystemInfo[] fsinfos=dinfo.GetFileSystemInfos();
foreach(FileSystemInfo fsinfo in fsinfos){
if(fsinfo is DirecotryInfo){
DirectoryInfo dirinfo=new DirectoryInfo(fsinfo.Fullname);
//...
}
else{
FileInfo finfo=new FileInfo(fsinfo.FullName);
//...
}
}

StreamWriter/StreamReader

1
2
3
4
5
6
7
StreamWriter sw=new StreamWriter("...",true);
sw.WriteLine("...");
sw.Close();

StreamReader sr=new StreamReader("...");
string str=sr.ReadToEnd();
sr.Close();

GDI+

Image

1
2
3
4
5
private void Form1_Paint(object sender,PaintEventArgs e){
Image myImage=Image.FromFile("*.jpg");
Graphics myGraphics=this.CreateGraphics();
myGraphics.DrawImage(myImage,50,20,90,92);
}

Bitmap

绘制出的图像可以自动刷新。

1
2
3
4
5
Bitmap bmp=new Bitmap(120,80);
Graphics g=Graphics.FromImage(bmp);
Pen myPen=new Pen(Color.Green,3);
g.DrawEllipse(myPen,50,10,120,80);
this.BackgroundImage=bmp;

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static int MyInt(string a,string b){
int int1,int2,num;
try{
int1=int.Parse(a);
int2=int.Parse(b);
if(int2==0){
throw new DivideByZeroException();
}
num=int1/int2;
return num;
}
catch(DivideByZeroException de){
Console.WriteLine(de.Message);
}
catch(Exception ex){
Console.WriteLine(ex);
}
finally{
return 0;
}
}

Socket

1
using System.Net;

Dns/IPAddress/IPHostEntry

1
2
3
4
5
6
7
8
9
10
11
12
13
string localname=Dns.GetHostName();//获取本机名
IPAddress[] ips=Dns.GetHostAddresses(localname);//获取本机所有IP
foreach(IPAddress ip in ips)
if(!ip.IsIPv6SiteLocal)//不是IPv6地址
localip=ip.ToString();//获取本机IP地址

try{
IPHostEntry host=Dns.GetHostEntry("192.168.1.50");
name=host.HostName.ToString();//目标主机名
}
catch(Exception ex{
MessageBox.Show(ex.Message);
}

TcpClient/TcpListener实战

Server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
namespace Server{
class Program{
static void Main(){
int port=888;
TcpClient tcpClient;
IPAddress[] serverIP=Dns.GetHostAddresses("127.0.0.1");
IPAddress localAddress=serverIP[0];
TcpListener tcpListener=new TcpListener(localAddress,port);
tcpListener.Start();
//服务器启动成功
while(true){
try{
tcpClient=tcpListener.AcceptTcpClient();
NetworkStream networkStream=tcpClient.GetStream();
BinaryReader reader=new BinaryReader(networkStream);
BinaryWriter writer=new BinaryWriter(networkStream);
while(true){
try{
string strReader=reader.ReadString();
string[] strReaders=strReader.Split(new char[]{' '});//strReaders[0]为客户端IP [1]为消息
//...
writer.Write("...");//发送消息
}
catch{
break;
}
}
}
catch{
break;
}
}
}
}
}

Client:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace Client{
class Program{
static void Main(string[] args){
TcpClient tcpClient=new TcpClient();
tcpClient.Connect("127.0.0.1",888);//连接服务器IP地址及端口
if(tcpClient!=null){
//连接成功
NetworkStream networkStream=tcpClient.GetStream();
BinaryReader reader=new BinaryReader(networkStream);
BinaryWriter writer=new BinaryWriter(networkStream);
string localip="127.0.0.1";
IPAddress[] ips=Dns.GetHostAddresses(Dns.GetHostName());
foreach(IPAddress ip in ips)
if(!ip.IsIPv6SiteLocal)
localip=ip.ToString();
writer.Write(localip+" ...");//发送消息
while(true){
try{
string strReader=reader.ReadString();
if(strReader!=null)
Console.WriteLine(strReader);//接收到的消息
}
catch{
break;
}
}
}
//连接失败
}
}
}

UdpClient

Server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace Server{
class Program{
static UdpClient udp=new UdpClient();
static void Main(string[] args){
udp.Connect("127.0.0.1",888);
while(true){
Thread thread=new Thread(()=>{
try{
Byte[] sendBytes=Encoding.Default.GetBytes("("+DateTime.Now.ToLongTimeString()+")...");//发送消息
udp.Send(sendBytes,sendByes.Length);
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
});
thread.Start();
Thread.Sleep(1000);
}
}
}
}

Client:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
namespace Client{
public partial class Form1:Form{
public Form1(){
InitializeComponent();
CheckForIllegalCrossThreadCalls=false;//其他线程中可以调用主窗体控件
}
bool flag=true;
UdpClient udp;
Thread thread;
private void button1_Click(object sender,EventArgs e){
udp=new UdpClient(888);
flag=true;
IPEndPoint ipendpoint=new IPEndPoint(IPAddress.Any,888);
thread=new Thread((=>{
while(flag){
try{
if(udp.Available<=0)//是否有网络数据
continue;
if(udp.Client==null)
return;
byte[] bytes=udp.Recieve(ref ipendpoint);
string str=Encoding.Default.GetString(bytes);//接收到的消息
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
Thread.Sleep(1000);
}
}));
thread.Start();
}
private void button2_Click(object sender,EventArgs e){
flag=false;
if(thread.ThreadState==ThreadState.Running)
thread.Abort();
udp.Close();
}
}
}

Thread

1
using System.Threading;

Start

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public partial class Form1:Form{
public Form1(){
InitializeComponent();
CheckForIllegalCrossThreadCalls=false;
}
void Roll(){
Thread.Sleep(1000);//线程休眠1000ms
th2.Join();//线程th1暂停th2开始
//th2.Join(1000); 等待线程th2退出或1000ms后自动退出
lock(this){//线程同步法一
//...
}
Monitor.Enter(this);//法二
//...
Monitor.Exit(this);
Mutex myMutex=new Mutex(this);//法三
myMutex.WaitOne();
//...
myMutex.ReleaseMutex();
//...
}
private void Form1_Load(object sender,EventArgs e){
Thread th1=new Thread(new ThreadStart(Roll));
th1.Name="线程一";
th1.Priority=ThreadPriority.Lowest;//BelowNormal Normal AboveNormal Highest
th1.Start();
//Thread th2=...;
//th2.Start();
th1.Suspend();//挂起
th1.Resume();//恢复挂起的进程
}
private void Form1_FormClosing(object sender,EventArgs e){
if(th1.ThreadState==ThreadState.Running)
th1.Abort();
}
}