|
原味的夏日
夏日里的一米阳光 |
什么是进程?
当一个程序开始运行时,它就是一个进程,进程包括运行中的程序和程序所使用到的内存和系统资源。而一个进程又是由多个线程所组成的。
什么是线程?
线程是程序中的一个执行流,每个线程都有自己的专有寄存器(栈指针、程序计数器等),但代码区是共享的,即不同的线程可以执行同样的函数。
什么是多线程?
多线程是指程序中包含多个执行流,即在一个程序中可以同时运行多个不同的线程来执行不同的任务,也就是说允许单个程序创建多个并行执行的线程来完成各自的任务。
多线程的好处:
可以提高CPU的利用率。在多线程程序中,一个线程必须等待的时候,CPU可以运行其它的线程而不是等待,这样就大大提高了程序的效率。
多线程的不利方面:
线程也是程序,所以线程需要占用内存,线程越多占用内存也越多; 多线程需要协调和管理,所以需要CPU时间跟踪线程; 线程之间对共享资源的访问会相互影响,必须解决竞用共享资源的问题;线程太多会导致控制太复杂,最终可能造成很多Bug;
接下来将对C#编程中的多线程机制进行探讨。为了省去创建GUI那些繁琐的步骤,更清晰地逼近线程的本质,接下来的所有程序都是控制台程序,程序最后的Console.ReadLine()是为了使程序中途停下来,以便看清楚执行过程中的输出。
任何程序在执行时,至少有一个主线程。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime;
using System.Threading;
namespace TransBall
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
///
private Point mouseOffset;
private bool isMouseDown = false;
private bool IfThreadStart;
Thread T1;
Thread T2;
Thread T3;
Thread T4;
Thread T5;
Thread T6;
private delegate void CALL(Control Tr);
private System.Windows.Forms.PictureBox btnExit;
private System.Windows.Forms.PictureBox btnStart;
private System.Windows.Forms.Label L1;
private System.Windows.Forms.Label L2;
private System.Windows.Forms.Label L3;
private System.Windows.Forms.Label L4;
private System.Windows.Forms.Label L5;
private System.Windows.Forms.Label L6;
private System.Windows.Forms.Label lblLast;
private System.ComponentModel.Container components = null;
public MainForm()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.L1 = new System.Windows.Forms.Label();
this.L2 = new System.Windows.Forms.Label();
this.L3 = new System.Windows.Forms.Label();
this.L4 = new System.Windows.Forms.Label();
this.L5 = new System.Windows.Forms.Label();
this.L6 = new System.Windows.Forms.Label();
this.btnExit = new System.Windows.Forms.PictureBox();
this.btnStart = new System.Windows.Forms.PictureBox();
this.lblLast = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// L1
//
this.L1.BackColor = System.Drawing.Color.Yellow;
this.L1.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.L1.Location = new System.Drawing.Point(114, 175);
this.L1.Name = "L1";
this.L1.Size = new System.Drawing.Size(21, 18);
this.L1.TabIndex = 0;
this.L1.Text = "1";
//
// L2
//
this.L2.BackColor = System.Drawing.Color.Yellow;
this.L2.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.L2.Location = new System.Drawing.Point(181, 173);
this.L2.Name = "L2";
this.L2.Size = new System.Drawing.Size(21, 18);
this.L2.TabIndex = 1;
this.L2.Text = "2";
//
// L3
//
this.L3.BackColor = System.Drawing.Color.Yellow;
this.L3.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.L3.Location = new System.Drawing.Point(249, 172);
this.L3.Name = "L3";
this.L3.Size = new System.Drawing.Size(21, 18);
this.L3.TabIndex = 2;
this.L3.Text = "3";
//
// L4
//
this.L4.BackColor = System.Drawing.Color.Yellow;
this.L4.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.L4.Location = new System.Drawing.Point(315, 171);
this.L4.Name = "L4";
this.L4.Size = new System.Drawing.Size(21, 18);
this.L4.TabIndex = 4;
this.L4.Text = "4";
//
// L5
//
this.L5.BackColor = System.Drawing.Color.Yellow;
this.L5.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.L5.Location = new System.Drawing.Point(382, 171);
this.L5.Name = "L5";
this.L5.Size = new System.Drawing.Size(21, 18);
this.L5.TabIndex = 5;
this.L5.Text = "5";
//
// L6
//
this.L6.BackColor = System.Drawing.Color.Yellow;
this.L6.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.L6.Location = new System.Drawing.Point(450, 170);
this.L6.Name = "L6";
this.L6.Size = new System.Drawing.Size(21, 18);
this.L6.TabIndex = 6;
this.L6.Text = "6";
//
// btnExit
//
this.btnExit.BackColor = System.Drawing.Color.White;
this.btnExit.Image = ((System.Drawing.Image)(resources.GetObject("btnExit.Image")));
this.btnExit.Location = new System.Drawing.Point(75, 11);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(17, 19);
this.btnExit.TabIndex = 7;
this.btnExit.TabStop = false;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click_1);
//
// btnStart
//
this.btnStart.BackColor = System.Drawing.Color.White;
this.btnStart.Image = ((System.Drawing.Image)(resources.GetObject("btnStart.Image")));
this.btnStart.Location = new System.Drawing.Point(7, 80);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(20, 17);
this.btnStart.TabIndex = 8;
this.btnStart.TabStop = false;
this.btnStart.Click += new System.EventHandler(this.pictureBox1_Click);
//
// lblLast
//
this.lblLast.BackColor = System.Drawing.Color.Yellow;
this.lblLast.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.lblLast.Location = new System.Drawing.Point(341, 18);
this.lblLast.Name = "lblLast";
this.lblLast.Size = new System.Drawing.Size(145, 18);
this.lblLast.TabIndex = 9;
this.lblLast.Text = "中奖号码:123456";
this.lblLast.Visible = false;
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.ClientSize = new System.Drawing.Size(496, 219);
this.Controls.Add(this.lblLast);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.L6);
this.Controls.Add(this.L5);
this.Controls.Add(this.L4);
this.Controls.Add(this.L3);
this.Controls.Add(this.L2);
this.Controls.Add(this.L1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "MainForm";
this.TransparencyKey = System.Drawing.Color.Yellow;
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseDown);
this.Load += new System.EventHandler(this.MainForm_Load);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseUp);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseMove);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
private void MainForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseOffset = new Point(-e.X, -e.Y);
isMouseDown = true;
}
}
private void MainForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (isMouseDown)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
this.Location = mousePos;
}
}
private void MainForm_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
private void btnExit_Click_1(object sender, System.EventArgs e)
{
this.Close();
Application.Exit();
}
private void pictureBox1_Click(object sender, System.EventArgs e)
{
if (IfThreadStart==false)
{
lblLast.Visible=false;
InThread A1 = new InThread();
A1.SetNumber(L1,1000);
T1 = new Thread(new ThreadStart(A1.RunInThread));
T1.Start();
InThread A2 = new InThread();
A2.SetNumber(L2,1111);
T2 = new Thread(new ThreadStart(A2.RunInThread));
T2.Start();
InThread A3 = new InThread();
A3.SetNumber(L3,2222);
T3 = new Thread(new ThreadStart(A3.RunInThread));
T3.Start();
InThread A4 = new InThread();
A4.SetNumber(L4,3333);
T4 = new Thread(new ThreadStart(A4.RunInThread));
T4.Start();
InThread A5 = new InThread();
A5.SetNumber(L5,4444);
T5 = new Thread(new ThreadStart(A5.RunInThread));
T5.Start();
InThread A6 = new InThread();
A6.SetNumber(L6,5555);
T6 = new Thread(new ThreadStart(A6.RunInThread));
T6.Start();
IfThreadStart=true;
}
else
{
T1.Abort();
T2.Abort();
T3.Abort();
T4.Abort();
T5.Abort();
T6.Abort();
IfThreadStart=false;
lblLast.Text ="中奖号码:"+L1.Text +L2.Text+L3.Text+L4.Text+L5.Text +L6.Text;
lblLast.Visible=true;
}
}
private void MainForm_Load(object sender, System.EventArgs e)
{
IfThreadStart = false;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace notepad
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
fontDialog1.ShowDialog();
richTextBox1.Font = fontDialog1.Font;
}
private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
fontDialog1.ShowDialog();
richTextBox1.ForeColor = fontDialog1.Color;
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = "e:\text.txt";
string content = richTextBox1.Text;
if (string.IsNullOrEmpty(path) == true)
{
MessageBox.Show("文件路径不正确");
return;
}
try
{
FileStream myfs = new FileStream(path, FileMode.Create);
StreamWriter mysw = new StreamWriter(myfs);
mysw.Write(content);
mysw.Close();
myfs.Close();
MessageBox.Show("创建成功");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message .ToString ());
}
}
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
string[] drivers = System.Environment.GetLogicalDrives();
foreach (string driver in drivers )
{
NewMethod(driver);
}
}
private static void NewMethod(string path)
{
string content;
try
{
FileStream myfs = new FileStream(path, FileMode.Open);
StreamReader mysr = new StreamReader(myfs);
content = mysr.ReadToEnd();
RichTextBox richtextbox = new RichTextBox();
richtextbox.Text = content;
mysr.Close();
myfs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message .ToString ());
}
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = "e:\\text.txt";
if (string.IsNullOrEmpty(path) == true)
{
MessageBox.Show("路径不正确");
}
File.Copy(path, "e:\\text.txt");
MessageBox.Show("保存成功");
}
private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.ShowDialog();
string path = (string )saveFileDialog1.Tag;
File.Copy("e:\\text.txt",path);
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void 日期ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.日期ToolStripMenuItem.Checked ==true )
{
this.dateTimePicker1.Show();
}
}
private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
{
bool c = false;
if (全选ToolStripMenuItem.Checked ==true )
{
this.richTextBox1.SelectAll();
全选ToolStripMenuItem.Checked = c;
}
}
public void 查找ToolStripMenuItem_Click(object sender, EventArgs e)
{
find f = new find();
string ss=richTextBox1.SelectedText.ToLower();
f.ss = ss;
f.Show();
}
}
}
查找
namespace notepad
{
public partial class find : Form
{
public find()
{
InitializeComponent();
}
private void find_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
public string ss = "";
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == null)
{
button1.Enabled = false;
}
else
{
button1.Enabled = true;
}
Form1 f = new Form1();
if (checkBox1.Checked==false)
{
string s = textBox1.Text.Trim().ToLower();
if (f.Text.LastIndexOf(ss) > f.Text.IndexOf(ss))
{
MessageBox.Show("exists");
}
}
}
}
}
namespace resRdminister
{
public partial class fillMain : Form
{
public fillMain()
{
InitializeComponent();
}
//点击浏览按钮
private void btnBrowse_Click(object sender, EventArgs e)
{
//OpenFileDialog ofd = new OpenFileDialog();
FolderBrowserDialog ofd = new FolderBrowserDialog();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.Cancel)
{
return;
}
string path = ofd.SelectedPath;
txtURL.Text = path;
DirectoryInfo di = new DirectoryInfo(path);
TreeNode treeNode = new TreeNode();
treeNode.Text = di.Name;
treeNode.Tag = di;
this.tvMain.Nodes.Add(treeNode);
FillTree(di,treeNode);
}
private void FillTree(DirectoryInfo diInfo, TreeNode tnode)
{
//XmlNodeList xnodeList = xnode.ChildNodes;
DirectoryInfo[] directoyInfo = diInfo.GetDirectories();
foreach (DirectoryInfo dis in directoyInfo)
{
TreeNode tree = new TreeNode();
tree.Text = dis.Name;
tree.Tag = dis;
tnode.Nodes.Add(tree);
FillTree(dis,tree);
}
}
//TreeView
private void tvMain_AfterSelect(object sender, TreeViewEventArgs e)
{
DirectoryInfo di = (DirectoryInfo)(e.Node.Tag);
FillListView(di);
}
//ListView
private void FillListView(DirectoryInfo disrctoryInfo)
{
this.lvMain.Items.Clear();
FileInfo[] fileinfo = disrctoryInfo.GetFiles();
DirectoryInfo[] di = disrctoryInfo.GetDirectories();
foreach (DirectoryInfo diInfo in di)
{
ListViewItem lvitem = new ListViewItem();
lvitem.Tag = diInfo;
lvitem.Text = diInfo.Name;
lvitem.SubItems.Add("文件夹");
lvitem.SubItems.Add(" ");
lvitem.SubItems.Add(diInfo.CreationTime.ToString());
this.lvMain.Items.Add(lvitem);
}
foreach (FileInfo Info in fileinfo)
{
ListViewItem lvitem = new ListViewItem();
lvitem.Tag = Info;
lvitem.Text = Info.Name;
lvitem.SubItems.Add(Info.Extension);
lvitem.SubItems.Add(Info.Length.ToString());
lvitem.SubItems.Add(Info.CreationTime.ToString());
this.lvMain.Items.Add(lvitem);
}
}
private void lvMain_DoubleClick(object sender, EventArgs e)
{
NewMethod();
}
private void NewMethod()
{
if (this.lvMain.SelectedItems[0] == null)
{
return;
}
try
{
DirectoryInfo di = (DirectoryInfo)(this.lvMain.SelectedItems[0].Tag);
FillListView(di);
}
catch (Exception)
{
FileInfo fi = (FileInfo)(this.lvMain.SelectedItems[0].Tag);
System.Diagnostics.Process.Start(fi.FullName);
}
}
private void attribute_Click(object sender, EventArgs e)
{
if (this.lvMain.SelectedItems[0] == null)
{
return;
}
Attribute att = new Attribute();
try
{
DirectoryInfo di = (DirectoryInfo)(this.lvMain.SelectedItems[0].Tag);
att.txtName.Text = di.Name;
att.lblType.Text = "文件夹";
att.txturl.Text = di.FullName;
// att.lblSize.Text = fi.Length.ToString();
att.lblCTime.Text = di.CreationTime.ToString();
att.lblMake.Text = di.LastWriteTime.ToString();
att.lblAccessTime.Text = di.LastAccessTime.ToString();
}
catch (Exception)
{
FileInfo fi = (FileInfo)(this.lvMain.SelectedItems[0].Tag);
att.txtName.Text = fi.Name;
att.lblType.Text = fi.Extension;
att.txturl.Text = fi.FullName;
att.lblSize.Text = fi.Length.ToString();
att.lblCTime.Text = fi.CreationTime.ToString();
att.lblMake.Text = fi.LastWriteTime.ToString();
att.lblAccessTime.Text = fi.LastAccessTime.ToString();
}
att.Show();
}
private void open_Click(object sender, EventArgs e)
{
NewMethod();
}
}
XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="程序集" value="StudentManager"/>
<add key="命名空间" value="StudentManager"/>
<add key="类" value="SqlStudentDAL"/>
</appSettings>
</configuration>
DBHelper
namespace StudentManager
{
public class DBHelper
{
/// <summary>
/// 获得连接字符串,使用sql数据库
/// </summary>
private static string constring ="server=.;uid=sa;database=StudentManager;pwd=";
/// <summary>
/// 执行增删改操作
/// </summary>
/// <param name="sql">传入增删改的sql语句</param>
/// <returns>返回受影响的行数</returns>
public static int ExecuteNonQuery(string sql)
{
int i=0;
using(SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand(sql,con))
{
con.Open();
i= cmd.ExecuteNonQuery();
con.Close();
}
}
return i;
}
/// <summary>
/// 执行查询操作
/// </summary>
/// <param name="sql">查询语句</param>
/// <returns>返回查询结果</returns>
public static SqlDataReader ExecuteReader(string sql)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
}
工厂类
public class Factory
{
public static IStudent CreateStudentDAL()
{
IStudent idal = null;
//从配置文件中加载程序集的名称
string 程序集 = System.Configuration.ConfigurationManager.AppSettings["程序集"];
string 命名空间 = System.Configuration.ConfigurationManager.AppSettings["命名空间"];
//从配置文件中加载数据访问层的名称
string 类 = System.Configuration.ConfigurationManager.AppSettings["类"];
//通过反射创建数据访问对象
idal = (IStudent)Assembly.Load(程序集).CreateInstance(命名空间+"."+类);
return idal;
}
}
form1
namespace StudentManager
{
public partial class Form1 : Form
{
// bool Flag = false;//标志位,表示用户是否选择过要修改或删除的数据行。
int id;
//通过工厂创建对象
IStudent studal = Factory.CreateStudentDAL();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 窗体加载时,显示所有信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ReadOnly = true;//不允许用户修改行
SE.SkinFile = Application.StartupPath + "\\skin\\OneGreen.ssk";
StudentView();
}
private void StudentView()
{
dataGridView1.DataSource = studal.GetAll();
}
//查看学生信息
private void btnView_Click(object sender, EventArgs e)
{
StudentView();
}
//添加学生信息
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtName.Text == "" || txtAge.Text == "")
{
MessageBox.Show("请将信息填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
try
{
int.Parse(txtAge.Text);
}
catch
{
MessageBox.Show("年龄必须为整数","输入错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
string name = txtName.Text;
if (studal.SelectByUserName(name))
{
MessageBox.Show("该学生已存在,请与管理员联系","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
return;
}
//添加学生方法1
string gender = radMale.Checked ? radMale.Text : radFemale.Text;
//父类引用指向子类,调用子类的方法
int i = studal.AddStudent(txtName.Text, txtAge.Text, gender, dtpCreateDate.Value);
//添加学生方法2
//StudentModel studentModel = new StudentModel();
//studentModel.Stuname = txtName.Text;
//studentModel.Gender = radMale.Checked ? radMale.Text : radFemale.Text;
//studentModel.CreateDate = dtpCreateDate.Value;
//int i = studal.AddStudent(studentModel);
if (i > 0)
{
MessageBox.Show("添加成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
// btnView.PerformClick();
StudentView();
}
else
{
MessageBox.Show("添加学生时产生了系统错误,请与管理员联系。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
}
//判断是否选中某行
private void dataGridView1_Click(object sender, EventArgs e)
{
//整行选中
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//判断是否选中某行
if (dataGridView1.SelectedRows.Count > 0)
{
int id = dataGridView1.CurrentRow.Index;
// int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
txtName.Text = dataGridView1.SelectedRows[0].Cells["Column2"].Value.ToString();
radMale.Checked = true;
if (dataGridView1.SelectedRows[0].Cells["Column3"].Value.ToString() == "女")
{
radFemale.Checked = true;
}
txtAge.Text = dataGridView1.SelectedRows[0].Cells["Column4"].Value.ToString();
dtpCreateDate.Text = dataGridView1.SelectedRows[0].Cells["Column5"].Value.ToString();
}
else {
MessageBox.Show("请先选中要更新的行","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
}
}
//更新学生信息
private void btnUpdate_Click(object sender, EventArgs e)
{
//获取当前选中的索引
id = int.Parse( dataGridView1.SelectedRows[0].Cells["Column1"].Value.ToString());
string sex = radMale.Checked ? radMale.Text : radFemale.Text;
try
{
int.Parse(txtAge.Text);
}
catch
{
MessageBox.Show("年龄必须为整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtName.Text == "" || txtAge.Text == "" || dtpCreateDate.Text == "")
{
MessageBox.Show("请输入详细的学生信息","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
return;
}
int i = studal.updateStudent(txtName.Text, txtAge.Text, sex, dtpCreateDate.Value, id);
if (i > 0)
{
MessageBox.Show("更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
StudentView();
}
else
{
MessageBox.Show("更新失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//删除学生信息
private void btnDelete_Click(object sender, EventArgs e)
{
//dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//if(Flag ==false)
//{
// MessageBox.Show("请选择要删除的行","提示",MessageBoxButtons .OK ,MessageBoxIcon.Warning );
// return;
//}
if (MessageBox.Show("确实要删除吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.No)
{
return;
}
id = int.Parse(dataGridView1.SelectedRows[0].Cells["Column1"].Value.ToString());
int i = studal.deleteStudent(id);
if (i > 0)
{
MessageBox.Show("删除成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
StudentView();
}
else
{
MessageBox.Show("删除失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//序列化查看
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = userable.getUser();
}
//序列化
private void button1_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("e:\\student.bat",FileMode .Create );
BinaryFormatter bf = new BinaryFormatter();
DataTable dt = (DataTable)dataGridView1.DataSource;
bf.Serialize(fs,dt);
dataGridView1.DataSource = null;
fs.Close();
fs.Dispose();
MessageBox.Show("已将数据序列化");
}
//反序列化
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("e:\\student.bat",FileMode .Open );
BinaryFormatter bf = new BinaryFormatter();
DataTable dt = bf.Deserialize(fs) as DataTable;
fs.Close();
fs.Close();
MessageBox.Show("反序列化成功");
}
}
DAL
namespace StudentManager
{
/// <summary>
/// 具体产品,连接到sql数据库
/// </summary>
public class SqlStudentDAL :IStudent
{
/// <summary>
/// 查询所有信息
/// </summary>
/// <returns>泛型集合</returns>
public List<StudentModel> GetAll()
{
string sql = "select * from Student";
List<StudentModel> list = new List<StudentModel>();
SqlDataReader reader = DBHelper.ExecuteReader(sql);
while(reader.Read())
{
StudentModel stuModel = new StudentModel();
stuModel.Id = reader["id"].ToString();
stuModel.Stuname = reader["stuname"].ToString();
stuModel.Gender = reader["Gender"].ToString();
stuModel.Age = reader["Age"].ToString();
stuModel.CreateDate = DateTime.Parse(reader["CreateDate"].ToString());
list.Add(stuModel);
}
reader.Close();
return list;
}
/// <summary>
/// 添加学生
/// </summary>
/// <param name="studentModel">传入学生类</param>
/// <returns>返回影响的行数</returns>
public int AddStudent(StudentModel studentModel)
{
string sql =string.Format( "insert into Student values('{0}','{1}',{2},'{3}')",studentModel.Stuname,studentModel.Gender,studentModel.Age,studentModel.CreateDate);
return DBHelper.ExecuteNonQuery(sql);
}
/// <summary>
/// 添加学生---------方法重载
/// </summary>
/// <param name="name">姓名</param>
/// <param name="age">年龄</param>
/// <param name="gender">性别</param>
/// <param name="crreateDate">日前</param>
/// <returns>返回影响的行数</returns>
public int AddStudent(string name, string age, string gender, DateTime crreateDate)
{
string sql = string.Format("insert into Student values('{0}','{1}',{2},'{3}')", name, gender, age, crreateDate);
return DBHelper.ExecuteNonQuery(sql);
}
/// <summary>
/// 根据用户名查找用户
/// </summary>
/// <param name="UserName">用户名</param>
/// <returns></returns>
public bool SelectByUserName(string name)
{
string sql = string .Format ("select * from Student where stuname='{0}'",name);
SqlDataReader reader = DBHelper .ExecuteReader (sql);
return reader.HasRows;
}
/// <summary>
/// 更新学生---------方法重载S
/// </summary>
/// <param name="studentModel">学生对象</param>
/// <returns>返回受影响的行数</returns>
public int updateStudent(StudentModel studentModel)
{
string sql = string.Format("update Student set stuname='{0}',Gender='{1}',Age='{2}',CreateDate='{3}' where id='{4}'", studentModel.Stuname, studentModel.Gender, studentModel.Age, studentModel.CreateDate, studentModel.Id);
return DBHelper.ExecuteNonQuery(sql);
}
public int updateStudent(string name, string age, string gender, DateTime crreateDate, int id)
{
string sql = string.Format("update Student set stuname='{0}',Age='{1}',Gender='{2}',CreateDate='{3}' where id='{4}'", name, age, gender, crreateDate, id);
return DBHelper.ExecuteNonQuery(sql);
}
/// <summary>
/// 执行删除操作
/// </summary>
/// <param name="id">要删除的行号</param>
/// <returns></returns>
public int deleteStudent(int id)
{
string sql = string.Format("delete from Student where id='{0}'",id );
return DBHelper.ExecuteNonQuery(sql);
}
}
}
namespace StudentManager
{
/// <summary>
/// 抽象产品
/// </summary>
public interface IStudent
{
List<StudentModel> GetAll();
//增加学生
int AddStudent(StudentModel studentModel);
int AddStudent( string name, string age, string gender, DateTime crreateDate);
//根据学生姓名查找用户信息
bool SelectByUserName(string name);
//更新学生信息
int updateStudent(StudentModel studentModel);
int updateStudent(string name, string age, string sex, DateTime crreateDate, int id);
//删除学生
int deleteStudent(int id);
}
}
创建序列化
namespace StudentManager
{
[Serializable]
public class userable
{
public static DataTable getUser()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("stuname");
dt.Columns.Add("Gender");
dt.Columns.Add("Age");
dt.Columns.Add("CreateDate");
DataRow row = dt.NewRow ();
row[0]=1;
row[1]="cn129";
row[2]="男";
row[3]=20;
row[4] = "2009-6-8";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 2;
row[1] = "cn123";
row[2] = "男";
row[3] = 23;
row[4] = "2009-6-8";
dt.Rows.Add(row);
return dt;
}
}
}
![]()
namespace StudentManager
{
//实体类,这个类的每一个对象,表示数据库中的一条记录,即一个学生
public class StudentModel
{
//封装字段
//学号
private string _id;
public string Id
{
get { return _id; }
set { _id = value; }
}
//姓名
private string _stuname;
public string Stuname
{
get { return _stuname; }
set { _stuname = value; }
}
//性别
private string _Gender;
public string Gender
{
get { return _Gender; }
set { _Gender = value; }
}
//年龄
private string _Age;
public string Age
{
get { return _Age; }
set
{
_Age = value;
}
}
//入学时间
private DateTime _CreateDate;
public DateTime CreateDate
{
get { return _CreateDate; }
set { _CreateDate = value; }
}
/// <summary>
/// 构造函数
/// </summary>
public StudentModel() { }
public StudentModel(string id,string stuname,string gender,string age,DateTime createDate)
{
this._id = id;
this._stuname = stuname;
this._Gender = gender;
this._Age = age;
this._CreateDate = createDate;
}
}
}
C# OOP 综合案例
1. 案例涉及的知识点
1. 类的定义
2. 类的成员
3. 属性的使用
4. 方法的使用
5. 类成员的封装
6. 类的继承
7. 多态特性
8. 方法重载
9. 构造函数
10. 抽象类和接口
11. 泛型集合
2. 重要知识点
1. 泛型集合
2. 工厂模式
3. 问题的描述
u 设计一个学生管理系统,运行程序后可以对学生进行管理,包括添加学生,查看学生信息。
u 为了便于扩展,该系统使用工厂模式实现用户对数据库的选择,目前可以提供SQL Sserver 2005 和Access 2003两种数据库。
4. 需求分析
根据问题描述,我们设计一个数据库,数据字典如下表:
数据库名称:StudentManager
|
表名 |
Student | ||
|
列名 |
描述 |
数据类型 |
约束 |
|
ID |
编号 |
Int |
主键,标识列 |
|
StuName |
姓名 |
Varchar(20) |
非空 |
|
Gender |
性别 |
Varchar(2) |
非空,且只能时男或女 |
|
Age |
年龄 |
int |
必须大于零 |
|
CreateDate |
入学时间 |
datetime |
默认为当天 |
5. 设计
1系统结构设计思路
1. 当界面(Form1)要添加学生时,要求工厂(Factory)帮助它创建一个具有添加学生能力的DAL对象(IStudent)
2. 工厂接到要求后,通过配置文件App.config来确认要向什么数据库中添加学生,并根据确认的结果创建一个DAL对象,并返回它的父类接口给界面,任务完成。
3. 界面接到工厂返回的DAL父类接口后,将界面上用户填写的数据传递给DAL的AddStudent方法
4. DAL接到数据后,将数据加工成有效的SQL语句,并把SQL语句交给DBHelper来执行
5. DBHelper得到SQL语句后将其执行,并将执行的结果反馈给DAL
6. DAL同样将结果反馈给界面,界面将结果反馈给用户。
2界面设计
6. 要求学员
1. 运行该程序,添加学生信息,观察程序运行状况。
2. 在添加按钮上设置断点跟踪程序运行,观察程序执行添加学生的流程。
3. 为代码添加注释:要求描述每个类的作用,每个方法的作用,方法每个参数的作用,方法返回值的作用。看不懂的地方做记号,等待老师讲解。
4. 寻找类中面向对象的知识(类的继承,数据封装,动态多态,方法重载,方法重写…)
5. 在老师已经提供的代码基础上在工厂框架内添加修改和删除学生的功能。
6. 自己重新独立完成该项目。
T1
会使用三层结构搭建项目
理解三层结构中各层之间的逻辑关系
礼节三层结构中每一层的主要功能
三层:表示层:用于显示数据和接收用户输入的数据
业务逻辑层:主要负责数据的传递和处理
数据访问层:主要实现对数据的保存和读取操作
搭建三层:搭建表示层、业务逻辑层、数据访问层,添加各层之间的关系,
表示层依赖业务逻辑层、业务逻辑层依赖数据访问层
T2
会使用DataSet在三层结构中传递数据
会自定义DataSet
会使用DateView
创建DataSet
a.通过DataAdapter的Fill()方法将数据直接填充到DataSet中;
b.DataSet ds=new DataSet();
DataTable dt=new DataTable();
DataColumn dc=new DataColumn("列名",typeof(数据类型));
dt.Columns.Add(dc);
DataRow dr=dt.NewRow();
dr["列名"]=;
dr["列名"]=;
dt.Rows.Add(dr);
ds.Tables.Add(dt);
c获取DataSet中的数据
ds.Talbes[""].Rows[0]["列名"];
或者将DataSet的数据直接绑定到控件上
一个DataSet中可以有多个DataTable,一个DataTable可以动态生成多个DataView
DataSet ds=new DataSet();
DataView dv=new DataView();
dv.Table=ds.Table[""];
dv.RowFilter=""; //筛选的条件
dv.sort=""; //排序条件
T3 用OOP实现三层结构
会使用实体类
会使用using语句实现高效的数据访问层
using关键字在C#中两种用途
一种作为指令,引入命名空间;一种作为语句,用于定义一个范围,在此范围末自动释放对象
T4
会使用异常处理
会使用VSTS(Visual Studio Team System)写测试单元
“异常”是程序在执行时发生的错误,错误原因来自三方面:代码错误(语法错误、逻辑错误)资源不可用(访问未经授权的资源)
在.NET平台下异常有两种:1用户应用程序引发的异常,派生于ApplicationException类2公共语言运行库引发的异常,派生于SystemExecption类
异常处理就是当我们的应用系统在运行时发生错误后,不论 这种错误有那种原因引起的,通过开发人员对预知错误的处理或CLR内部的处理,使系统
能够恢复运行的过程。(遇到错误时,程序继续运行,而不是终止)
使用throw关键字再次引发由try...catch...块捕获到的异常,再次引发异常有助于我们在调试时获得更多的信息
软件开发中的单元测试是对整个项目中的某一个模块或模块中的某一个类、或某类中的某一个方法的测试。
在软件开发在中使用单元测试的好处是:有助于发现软件在研发前期的缺点,是确保软件质量的具体操作方法
VSTSd单元测试是VSTS平台中集成的单元测试框架(Team Test),支持:
生成测试代码框架,在IDE中运行测试,合并从数据库中加载数据的测试,测试运行完成后,进行代码分析覆盖
用VSTS写单元测试:创建测试,编写测试,运行测试
T5
会使用抽象工厂设计模式
有关面向对象的论文
C# 面向对象
面向对象技术是一种强有力的软件开发方法,它将数据和对数据的操作作为一个相互依赖,不可分割的整体,力图使现实世界的问题简单化,面向对象有三大特征:封装、继承、多态。
面向对象分析中,对象拥有的各种特征称为状态,对象所拥有能做的事情称为行为,一组具有相同特征和共同行为的对象的集合称之为类。可以说类是对象的抽象,类是对象的末班,对象是类的实例。类的成员包括字段、属性、方法、构造函数、索引器等。通过访问修饰符可以控制程序对类成员的访问。访问修饰符有以下4个:
Public 可被其他对象访问,没有任何限制; private 只有对象自己可以访问;
Protected 类内部及其子类可以访问; internal 在同一程序集中被访问;
通过访问修饰符保护了类成员的访问级别。
类的属性来约束对字段的非法输入,可以设置读写属性:只读,只写,读写,通过get()和set()方法来限制它的访问类型。避免使用非法数据赋值,保证数据完整性,避免类内部发生修改时导致整个程序的修改,我们就可以通过封装来限制类的访问级别。利用公有属性访问私有字段来实现。
一个对象访问另一个对象的属性和方法,这种关系当他们的互相访问结束时就不复存在了,要想建立类之间的关系,实现代码复用,方便系统的扩展,我们就要用到面向对象的第二特征:继承。
一个类可以继承另一个类,被继承的类称为父类或基类,继承其他类的类称为子类或者派生类。继承后子类不仅拥有自己独有的成员,换拥有父类所有的非私有成员,因此使用继承简化了类的设计,减少了代码的冗余。在继承后,如果在子类定义的一个方法其名称、返回类型、及参数列表正好和父类中某个方法的其名称、返回类型、及参数列表相匹配,那么可以说子类重写了父类的方法。类有一个成员,它是一个特殊的方法,它通常在类的最前面叫做构造函数。它用于创建实例时对对象进行初始化,构造函数可以重载,可以初始化不同数量的属性,这样传入的参数数量不同。父类包含两种构造函数:有参的和无参的。一个子类继承父类,如果子类的构造函数没有使用base关键字指明调用父类的那个构造函数,则父类必须提供一个默认的无参的构造函数,这种情况下子类会隐式调用父类的默认无参构造函数;如果父类中没有提供默认的无参的构造函数,那么子类的构造函数必须明确指明调用哪个父类的有参构造函数。
继承有三个特性:1传递性,要符合is-a关系;2密封类,用sealed修饰的类不能被继承;3单根性,一个类只能有一个直接父类,但可以实现多个接口,接口中可以定义属性方法,但不能够实现,接口可以作为参数或返回值。
相同的方法调用可实现不同的实现方式这就是多态。两个或多个属于不同类的对象对与统一方法的调用做出不同的响应方式。多态分为静态多态和动态多态。方法重载是指两个或多个方法名称相同,但参数项不同,它属于静态多态。它的重载方式有两种:参数是不同类型的重载和参数个数不同的重载;动态多态可以通过抽象方法和虚方法实现。抽象方法是一个没有实现的方法用abstract修饰,含有抽象方法的类必然是抽象类。抽象类不能被实例化,不能是密封或静态的;当一个抽象父类派生出一个子类时,子类将继承父类的所有特征。包括未实现的抽象方法,在子类中实现一个抽象方法是使用override关键字来重写抽象方法。用virtual关键字修饰的方法称为虚方法。虚方法可以有具体的实现,也可以被重写,从而实现多态性。
面向对象的三大特征:封装、继承、多态。面向对象编程(Objec-Oriented Programm OOP)保证对象自身数据的完整性、安全性,相同的方法调用实现不同的实现方式,建立了类之间的关系。实现了代码的复用,方便了系统的扩展。