c#基础语法
0.语法基础
0.1 基础概念
变量三要素
变量类型:规定变量的数据类型
变量名:有意义,好记忆
变量值:变量对应的内存数据
数据类型
int:整型
double:浮点型
string:用于存储一段字符
bool:用于表示一个条件是否成立
datetime:用于存储日期和时间
变量声明和赋值
int age ;
age=20;
//声明的同时给变量赋值
string name ="小红";
//变量的使用
Console.WriteLine("我叫"+name+"今年"+age+"岁");
变量命名规范
- 命名尽量用对应的英文命名,比如年龄使用age,除循环变量外尽量不用单个字符
- 严格区分大小写
- 驼峰命名法:当使用一个或者多个单词组成变量名时,要使用camel命名法,即第一个单词的首字母小写,其它单词的首字母大写,如stuName。
- 常量的定义语法:
const 数据类型 常量名称=值;
const double PAI=3.14; - 枚举
访问修饰符(一般public)enum 枚举名{值1,值2…}
- 枚举中不能包含方法,一般在类的外部
console类的使用
Console.WriteLine()//换行
Console.WriteLine("内容")//输出内容换行
Console.Write()//输出内容不换行
字符串格式化
Console.WriteLine("姓名:{0} 年龄:{1}",stuName,stuAge);
0.2 强制转换
- 字符串和值转换
int stuAge =int.Parse(Console.ReadLine());
double a=double.parse(“20.5”);
float b=float.parse(“20.25”);
int c =int.pase(“20”); - 值类型强转换成字符串类型
string aa=a.tostring();
string bb=b.tostring();
strign cc=c.tostring(); - 数值跟数值之间转换
double a=2.31;
int b=20;
int result=(int)a+b; - 使用万能转换器进行不同类型的转换
double a=convert.todouble(“20.21”);
float b=convert.tosingle(“20.55”);
int c =convert.toint32(“20”);
DateTime datetime=convert.toDateTime(“2023-02-02”);
int d=convert.toint32(a);
int e=convert.toint32(b);
double f=convert.todouble©; - 两次强制转换
从浮点类型的字符串到int需要两次强制转换
int a=(int)double.parse(“35.34”);
int b=(int)convert.todouble(“34.33”);
快捷键
consol.writeline()//cw按两个tab键
0.3 选择结构
if选择结构
int a= 10;
int b=20;
bool result;
if(a<b)
result=true;
else
result=false;
console.writeline("a>b的比较结果是"+result);
三元运算符
int a=10;
int b=20;
bool result=a>b?true:false;
console.writeline ("a>b的比较结果是:"+result);
if嵌套结构
static void main(stirng []args)
{
console.writeline("请输入客户消费信息:");
int totomaoney =int.parse(console.readline());
if(totalMoney>=1000)
{
console.writeline("需付款:"+tottalmoney*0.8);
conosle.wirte("您的会员类型:");
string customerType=console.readline();
if(customerType=="普通")
{
console.write(同时送您100代金券)
}
else if(customerType=="vip"){
console.wirteline("同时送您200代金券");
}
}
else{
console.wirteline("需付款:"+totalmoney);
}
}
switch 选择结构
常用的语法结构
switch(表达式)
{
case 常量1:
语句;
break;
case 常量2;
语句;
break;
......
defalt://如果没有找到匹配结果
语句;
break;
}
例子:
static viod main(stirng[]args)
{
console.writeline("请输入您购买的电器品牌:");
string band=console.readline();
switch (band)
{
case"A":
console.writeline("赠送您热水器一台");
break;
case"B":
consle.wirteline("赠送手机一部");
break;
case"C":
console.wirteline("赠送音箱一个");
break;
default:
console.witeline("无赠品");
break;
}
console.readline();
}
for循环
class Program
{
static void Main(string[] args)
{
for (int a=1; a <= 9; a++){
for (int b=1; b <= a; b++){
Console.Write("{0}*{1}={2}\t", a, b, a * b);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
while循环
break跳出整个循环
continue跳出
static void Main(string[] args)
{
int count = 0;
while (count < 5)
{
Console.WriteLine("当前队员的成绩:");
int score = int.Parse(Console.ReadLine());
if (score < 60)
{
continue;
}
count++;
Console.WriteLine("该队员姓名:");
Console.ReadLine();
}
Console.WriteLine("队员已招满!");
Console.ReadLine();
}
调试
- 插入断点(双击所在行的侧边)
- 单行运行:F11
- 逐过程运行:F10
- 停止调试:shift+F5
程序调试的思路和详细步骤
- 设置断点::分析可能出现错误的位置,并设置断点
- 调试运行:启动调试,单步运行
- 观察变量:不断观察特定变量的值
- 分析问题:通过观察变量的值,发现问题
- 修改代码:重新运行
04. 字符串的处理
length使用
字符串的长度
static void Main(string[] args)
{
string usrName = "123aga";
int pwdLength = usrName.Length;
Console.WriteLine(pwdLength);
Console.ReadLine();
}
比较字符串内容是否相等
使用"=="或者"equals()"方法,优先使用equals()
static void Main(string[] args)
{
string name1 = "iris";
string name2 = "iris";
string name3 = "tom";
bool a = name1.Equals(name2);
bool b =name1.Equals(name3);
Console.WriteLine(a);
Console.WriteLine(b);
Console.ReadLine();
}
字符串截取
substring
static void Main(string[] args)
{
string email = "xiaoqiang@qq.com";
string name = email.Substring(0,email.IndexOf("@"));
Console.WriteLine("用户姓名: "+name);
string emailType = email.Substring(email.IndexOf("@")+1);
Console.WriteLine("邮箱类型是:"+emailType);
Console.ReadLine();
}
}
** 字符格式化Format()方法与其类似**
string newstring =string.format("格式字符串",参数列表)
static void Main(string[] args)
{
string name = "xiaohong";
string emailtype = "qq.com";
string info = "姓名是:{0},邮箱是:{1}";
info = string.Format(info,name,emailtype);
Console.WriteLine(info);
Console.ReadLine();
}
字符串为空
1. name.Length==0;
2. name== string.Empty;
3. name=="";
空字符串的使用方法
if(name==""){}
if(name.Equals(string.Empty)){}
- 注意null和”“的区别
去掉前后多余空格
string name =" name ";
name=name.Trim();
转换成大小写
string ToUpper();
string ToLower();
找到最后一个匹配项所在的索引位置
LastIndexOf(string value)
字符串 拼接
string a="我是";
string b="小强";
string c="的弟弟";
//1. 直接+
string c=a+b;
//. stringbuilder.append()
1. 类和对象
### 1. 1 字段和属性比较
字段(成员变量)
- 字段主要是为类的内部做数据交互使用,字段一般都是private
- 字段可以赋值,也可以取值
- 当字段需要为外部提供数据的时候,请将字段封装为属性,而不是使用共有字段,这是面向对象提倡的。
属性
- 属性一般是向外提供数据,主要是描述对象的静态特征,所以,属性一般是public
- 属性可以根据需求设置只读、只写,提高数据安全性
- 属性内部可以添加我们需要的业务逻辑,从而避免非法数据。
//属性
private double salary ;//薪水
public double Salary{
get{return salary;}
set{salary==value;}
}
//标准属性的简化
public double Salary {get;set;}
1. 2 方法和方法的重载
1.2.1 什么是方法
【概念】:对象的动态特征就是方法,方法表示这个对象能够做什么
【类型】:实例方法、静态方法、(构造方法、抽象方法、虚方法)
定义规范
访问修饰符 返回值类型 方法名(参数1,参数2...)
{
//方法主题
return 返回值;//如果没有返回值,则不需要该语句
}
//例
public string GetStudent(){
strign info=string.Format("姓名:{0} 学号:{1}",studentName,studentId);
return info;
}
注意事项
- 访问修饰符:可以省略,默认private,可以根据需要定义成public
- 方法名:一般是”动词“或者”动宾短语“,采用Pascal,首字母大写,不能以数字开头
- 参数列表:根据需求添加
- 有返回值的使用return 语句,return后不能再有其它语句
- 没有返回值的用void修饰
变量的分类及作用域
- 在方法内部的变量,称为“局部变量”,只能在该方法的内部使用
- 在方法外部,类的内部定义的变量,称为“成员变量”(也叫字段),可以在类的内部或外部使用(很少在外部使用)
1.2.2 方法的重载
重载方法的调用特点
编译器将根据方法的参数个数和类型自动匹配对应方法
方法重载的好处
- 减少类的对外接口(只显示一个方法),降低类的复杂度。
- 便于用户的使用(相同功能的方法名称一样)和识别。
方法重载的条件
- 方法的名称必须一样
- 方法的参数个数或类型不一样
方法重载的无关性
- 方法重载和返回值无关
public double Add(double a,double b)
{return a+b;}
public double Add(int a,double b){
return a+b;
}
public int Add(int a,int b){
return a+b;
}
//注意,如果
public double Add(int a, int b){
return a+b;//不构成方法重载,与返回值无关
}
静态方法
关键字static的使用
关键字可以修饰类、方法、成员变量,修饰后我们称之为:静态类、静态方法、静态字段
静态方法的调用:类名.方法名
使用示例
public static int Add(int a, int b, int c){
return a+b+c;
}
- 静态成员使用经验
- 静态成员在程序运行时被调入内存中,并且在系统未关闭之前不会被回收
- 类的成员使用非常频繁时候,可以使用static修饰,但是不能使用过多
- 静态成员不能直接调用实例成员(静态方法不能直接调用实例方法)
- 静态方法也可以重载
1.3 构造方法
有参构造方法使用总结
参数的类型和顺序同样需要和定义规范一直
有参数的构造方法可以让用户轻松选择使用何种方式完成对象的初始化工作
使用有参构造方法能够有效避免用户单个初始化对象属性的麻烦
如果想约束用户对象时必须完成某些属性的初始化工作,则可以去掉无参构造方法。
class Student{ //两个参数构造器 public Student(int stuId,string stuName){ this StudentId =stuId; this.StudentName=stuName; } //无参构造器 public Student(){ } //三个参数构造器 public Student(int stuId,string stuName, int age){ this StudentId =stuId; this.StudentName=stuName; this.Age=age; } }
构造方法PK实例方法
- 构造方法
- 用于对象的初始化,一个类中至少有一个构造方法
- 不能显示调用,只能在创建对象的时候,使用new来调用
- 构造方法不能有返回值
- 构造方法名称必须与类名一样
- 实例方法
- 用于表示对象能够干什么,一个类中可以没有任何实例方法
- 只能显示调用:对象名.方法名。
- 可以有返回值,没有时必须以void表示。
- 方法命名要有意义,一般是“动词+名词”形式,不能与类名相同,命名规范通常采用pascal命名法。
1.4 对象的销毁
对象的生命周期
对象在内存中不断的“生生死死”,具有生命周期。
对象在内存中的状态
- 正在引用:程序正在使用的对象
- 游离状态:没有引用的对象,已经使用完毕但是依然占据空间
垃圾回收机制
- .NET虚拟机特有机制,自动运行,并检查对象的状态
- 发现对象不再引用时,会将其释放所占用的空间(销毁)
1.5 对象的数据类型
值类型数据变量在传递的时候是将自己复制一份,
static void Main (string[]args){
int a=50;
int b=a;
b+=5;
}
引用数据类型(对象类型)
引用数据类型变量传递时,将自己内存地址赋给新变量
static void Main(string[]args){
Student objStu1=new Student();
Student objStu2=objStu1;
objStu2.Age=25;
}
2. 关键字
2.1 this关键字
- 当成员变量和局部变量重名时使用this区分
public Student (int StudentId, string studentName)
{
this.studentId=studentId;
this.studentName=studentName;
}
- this表示当前类的对象,用于访问该类成员变量或方法
public strign GetStudent(){
return string.Format{"姓名:{0} 学号:{1}",this.studentName,this.studentId}
}
2.2 ref关键字
使用ref关键字可以将值类型按照引用方式传递
平时不建议使用
static void Main (string []args){
int a=10;
int result=Square(ref a);
Console.WriteLine("a的平方={0} a的值={1}",result,a);
Console.ReadLine();
}
static int Square(ref int num1){
num1=num1*num1;
return num1;
}
2.3 out关键字
- 使用out关键字可以让方法有多个返回值
不建议使用,多参数返回时,主要使用字典集合
static void Main(string[] args)
{
int a = 10;
int square = 0;
int result = Operation(a, out square);
Console.WriteLine("a的平方={0 }a的立方={1}",square,result);
Console.ReadLine();
}
static int Operation (int num1,out int square)
{
square = num1 * num1;
int result = num1 * num1 * num1;
return result;
}
3.集合
3.1泛型集合List
List泛型集合的特点
- 表示泛型,T是Type的简写,表示当前不能确定的类型。
- 可以根据用户的实际需要,确定当前集合需要存放的数据类型,一旦确定就不可改变。
泛型集合要求
- 使用泛型集合只能添加一种类型的数据,数据取出后无需强制转换。
static void Main(string[] args)
{ //创建几个学员对象
Student objStu1 = new Student(1001, "小王");
Student objStu3 = new Student(1003, "小刘");
Student objStu4 = new Student(1004, "小李");
//创建集合对象
List<Student> stuList = new List<Student>();
stuList.Add(objStu1);
stuList.Add(new Student(1002, "小张"));
stuList.Add(objStu3);
stuList.Add(objStu4);
//获取元素个数
Console.WriteLine("元素总数:{0}",stuList.Count);
//删除一个元素
stuList.Remove(objStu3);
stuList.RemoveAt(2);
//插入一个对象
stuList.Insert(1, new Student(1006, "小花"));
List<string> nameList = new List<string> { "小红", "小米", "小花" };
//遍历集合
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentId+"\t"+item.StudentName);
}
foreach(string item in nameList)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public Student(int StudentId,string StudentName) {
this.StudentId = StudentId;
this.StudentName = StudentName;
}
public Student() { }
public string GetStudent()
{
string info = string.Format("姓名:{0}学号:{1}",StudentName,StudentId);
return info;
}
3.2 泛型集合Dictionary<K,V>
关于Dictionary<K,V>泛型集合
- Dictionary<K,V>通常称为字典,<K,V>约束集合中元素类型。
- 编译时检查类型约束,无需装箱拆箱操作,与哈希表操作类似。
static void Main(string[] args)
{ //创建几个学员对象
Student objStu1 = new Student(1001, "小王");
Student objStu3 = new Student(1003, "小刘");
Student objStu4 = new Student(1004, "小李");
Dictionary <string,Student> stu = new Dictionary<string,Student>();
stu.Add("小王", objStu1);
stu.Add("小刘", objStu3);
stu.Add("小李", objStu4);
foreach(string key in stu.Keys)
{
Console.WriteLine(key);
}
foreach(Student value in stu.Values)
{
Console.WriteLine(value.StudentId+"\t"+value.StudentName);
}
Console.ReadLine();
}
3.3 集合中对象的默认排序
字符串和值类型排序
static void Main(string[] args)
{ //字符串类型
List<string> nameList = new List<string>() { "小红","小白","小米"};
foreach(string item in nameList)
{
Console.WriteLine(item);
}
Console.WriteLine("---排序后");
nameList.Sort();
foreach(string item in nameList)
{
Console.WriteLine(item);
}
Console.WriteLine("---反转");
nameList.Reverse();
foreach(string item in nameList)
{
Console.WriteLine(item);
}
//值的类型
List<int> ageList = new List<int>() { 20, 10, 3 };
ageList.Sort();
foreach(int item in ageList)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
集合中对象的动态排序
static void Main(string[] args)
{
//对象类型
Student objStu1 = new Student(1001,"小红");
Student objStu2 = new Student(1003, "小白");
Student objStu3 = new Student(1002, "小米");
List<Student> stuList = new List<Student>() { objStu1, objStu2, objStu3 };
//默认排序
stuList.Sort();
Console.WriteLine("----------默认排序");
foreach(Student item in stuList) {
Console.WriteLine(item.StudentId+"\t" +item.StudentName);
}
Console.WriteLine("----------id升序排序");
stuList.Sort(new StuIdASC());
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentName);
}
Console.WriteLine("----------id降序排序");
stuList.Sort(new StuIdDESC());
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentName);
}
Console.WriteLine("----------name升序排序");
stuList.Sort(new StuNameASC());
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentName);
}
Console.WriteLine("----------name降序排序");
stuList.Sort( new StuNameDESC());
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentName);
}
Console.ReadLine();
}
class Student:IComparable<Student>//默认排序,只能一种
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public Student() { }
public Student(int StudentId,string StudentName) {
this.StudentId = StudentId;
this.StudentName = StudentName;
}
public int CompareTo(Student other)
{
// throw new NotImplementedException();
return other.StudentId.CompareTo(this.StudentId);
}
}
#region 排序类
//添加4个排序类并且分别实现排序接口
class StuNameASC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return x.StudentName.CompareTo(y.StudentName);
}
}
class StuNameDESC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return y.StudentName.CompareTo(x.StudentName);
}
}
class StuIdASC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return x.StudentId.CompareTo(y.StudentId);
}
}
class StuIdDESC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return y.StudentId.CompareTo(x.StudentId);
}
}
#endregion
集合排序总结
- 如果是基本数据类型,可以直接排序
- 如果是对象类型元素
- 当排序只有一种的时候,可以使用默认比较器
IComparable <T>在类中直接实现接口即可。 - 当需要多种排序的时候,需要添加对应排序类,并给每一个排序类实现比较器接口
ICompare<T>来完成不同排序方法。
- 当排序只有一种的时候,可以使用默认比较器
4. Winform开发环境的使用
4.1 事件驱动机制
C/S架构应用程序(Windows、WinForm、桌面应用程序):客户端/服务器(Client/Server)
- 客户端向服务器发出请求,服务器处理请求并将响应发送给客户端。
- 应用程序全部或部分部署在客户端,数据库或部分程序在服务器端。
案例
//三个按钮关联一个方法
this.btnAndy.Click += new System.EventHandler(this.btnTeacher_Click);
this.btnJuly.Click += new System.EventHandler(this.btnTeacher_Click);
this.btnIris.Click += new System.EventHandler(this.btnTeacher_Click);
//sensor表示事件源
private void btnTeacher_Click(object sender,EventArgs e)
{
MessageBox.Show(((Button)sender).Text+"你好!");
}
常用控件的事件
- 窗体事件
- load:窗体加载事件(应用较少)
- FormClosing:窗体关闭之前发生的事件
- FormClosed:窗体关闭之后发生的事件
- 文本框事件
- TextChanged:文本框内容改变时间
- KeyPress:用户按下某键并释放的时候发生的事件
- MouseLeave:当鼠标离开文本框的时候发生
- 下拉框事件
- SelectedIndexChanged:当用户选择的下拉项改变的时候发生
- 、
4.2 消息提示机制
消息提示框(不要经常使用)
Message.Show("请输入学员姓名!");
Message.Show("请输入学员姓名!","验证提示");
Message.Show("请输入学员姓名!","验证提示",MessageBoxButtons.OKCancel);
Message.Show("请输入学员姓名!","验证提示",MessageBoxButtons.OKCancel,MessageBoxButtons.Information);
//用户判断的消息框
DialogResult result = MessageBox.Show("请输入学员姓名", "验证提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result == DialogResult.Cancel)
{
MessageBox.Show(((Button)sender).Text + "用户取消操作");
}
else
{
MessageBox.Show("用户继续操作");
}
4.3项目框架基础搭建与用户登录窗体设计
窗体大小调节:FormBorderStyle --FixedSingle(固定不可调)
**窗体最大化**MaximizeBox:False(不可最大化)
左上角图表icon ,选择图片
启动位置:startposition–centerscreen
picturebox:窗体中添加图片
image:按钮添加图片
视图-tab键顺序:改变鼠标顺序
5. 文件操作
5.1 文本文件操作
文件写入
using System.IO;
private void button1_Click(object sender, EventArgs e)
{
//创建文件流
FileStream fs = new FileStream("D:\\file.txt", FileMode.Create);
//创建写入器
StreamWriter sw = new StreamWriter(fs);
//以流的方式写入数据
sw.Write(this.textBox1.Text.Trim());
//关闭写入器
sw.Close();
//关闭文件流
fs.Close();
}
//文件逐行写入,模拟逐行写入系统日志
//创建文件流
FileStream fs = new FileStream("D:\\file.txt", FileMode.Append);
//创建写入器
StreamWriter sw = new StreamWriter(fs);
//以流的方式逐行写入数据
sw.WriteLine(DateTime.Now.ToString()+"文件操作正常!");
//关闭写入器
sw.Close();
//关闭文件流
fs.Close();
文件读取
using System.IO;
private void button1_Click(object sender, EventArgs e)
{
//创建文件流
FileStream fs = new FileStream("D:\\file.txt", FileMode.Open);
//创建读取器(encoding.default防止乱码)
StreamReader sr = new StreamReader(fs,Encoding.Default);
//以流的方式写入数据
this.textBox1.Text=sr.ReadToEnd();
//关闭读取器
sr.Close();
//关闭文件流
fs.Close();
}
文件删除复制移动
//删除文件
private void btnAndy_Click(object sender, EventArgs e){
File.Delete(this.txtFrom.Text);
}
//复制文件
private void btnJuly_Click(object sender, EventArgs e)
{
if (File.Exists(this.txtTo.Text.Trim())) {
File.Delete(this.txtTo.Text);
}
File.Copy(this.txtFrom.Text.Trim(), this.txtTo.Text.Trim());
}
//移动文件
private void btnIris_Click(object sender, EventArgs e)
{
if (File.Exists(this.txtTo.Text.Trim()))
{
File.Delete(this.txtTo.Text.Trim());
}
if (File.Exists(this.txtFrom.Text.Trim()))
{
File.Move(this.txtFrom.Text.Trim(), this.txtTo.Text.Trim());
}
else
{
MessageBox.Show("文件不存在");
}
}
//获取指定目录下的文件
string[] files = Directory.GetFiles("D:\\files");
this.txtContent.Clear();
foreach (string item in files)
{
this.txtContent.Text += item + "\r\n";
}
//获取指定目录下的所有子目录
string[] dirs = Directory.GetDirectories("D:\\files");
this.txtContent.Clear();
foreach(string item in dirs)
{
this.txtContent.Text += item + "\r\n";
}
//删除指定目录下的所有子目录和文件
Directory.Delete("D:\\Myfiles0");//要求目录必须为空
//使用DirectoryInfo对象,可以删除不为空的目录
DirectoryInfo dir = new DirectoryInfo("D:\\Myfiles0");
dir.Delete(true);
对象保存
Student objStudent = new Student()
{
StuName = this.txtFrom.Text.Trim(),
StuAge = Convert.ToInt32(this.txtTo.Text.Trim()),
StuGender = this.txtGender.Text.Trim(),
Birthday = Convert.ToDateTime(this.txtBirthday.Text.Trim())
};
//保存到文件里
FileStream fs = new FileStream("objStudent.obj", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//一行一行写入
sw.WriteLine(objStudent.StuName);
sw.WriteLine(objStudent.StuAge);
sw.WriteLine(objStudent.StuGender);
sw.WriteLine(objStudent.Birthday);
//关闭对象
sw.Close();
fs.Close();
class Student
{
public string StuName{get;set;}
public int StuAge { get; set; }
public string StuGender { get; set; }
public DateTime Birthday { get; set; }
}
读取并显示数据
FileStream fs = new FileStream("objStudent.obj", FileMode.Open);
StreamReader sr = new StreamReader(fs);
Student objStudent = new Student() {
StuName = sr.ReadLine(),
StuAge = Convert.ToInt32(sr.ReadLine()),
StuGender = sr.ReadLine(),
Birthday = Convert.ToDateTime(sr.ReadLine())
};
sr.Close();
fs.Close();
//一行一行写入
this.txtFrom.Text = objStudent.StuName;
this.txtTo.Text = objStudent.StuAge.ToString();
this.txtGender.Text = objStudent.StuGender ;
this.txtBirthday.Text = objStudent.Birthday.ToShortDateString();
5.对象序列化和XML文件
5.1对象序列化和反序列化
使用文本
- 当对象属性发生变化是,需要增加或减少信息的写入或读取次数。
- 信息安全性较差
序列化
开头需要添加
using System.Runtime.Serialization.Formatters.Binary;
Student objStudent = new Student()
{
StuName = this.txtFrom.Text.Trim(),
StuAge = Convert.ToInt32(this.txtTo.Text.Trim()),
StuGender = this.txtGender.Text.Trim(),
Birthday = Convert.ToDateTime(this.txtBirthday.Text.Trim())
};
//创建文件流
FileStream fs = new FileStream("objStudent.stu", FileMode.Create);
//创建二进制格式化器
BinaryFormatter formatter = new BinaryFormatter();
//调用序列化方法
formatter.Serialize(fs, objStudent);
//关闭文件流
fs.Close();
}
//声明该对象可序列化
[Serializable]
class Student
{
public string StuName{get;set;}
public int StuAge { get; set; }
public string StuGender { get; set; }
public DateTime Birthday { get; set; }
}
反序列化
//创建文件流
FileStream fs = new FileStream("objStudent.stu", FileMode.Open);
//创建二进制格式化器
BinaryFormatter formatter = new BinaryFormatter();
//调用反序列化方法
Student objStudent = (Student)formatter.Deserialize(fs);
//关闭文件流
fs.Close();
//显示数据
this.txtFrom.Text = objStudent.StuName;
this.txtTo.Text = objStudent.StuAge.ToString();
this.txtGender.Text = objStudent.StuGender;
this.txtBirthday.Text = objStudent.Birthday.ToShortDateString();
5.2 XML文件操作
XML是eXtensible Markup Language的缩写,即可扩展语言。它是一种可以用来创建自定义的标记语言,由万维网协会(W3C)创建,用来客服HTML的局限。
从使用功能上看,XML主要是用于数据的存储,而HTML主要用于数据的显示。
- XML文档的格式要求
- 确定且唯一的根元素
- 开始标签和结束标签匹配
- 元素标签的正确嵌套
- 属性值要用引号括起来
- 同一个元素的属性不能重复
- XML语法要求
- 元素:<标签>文本内容</标签>
- 处理指令:<?xml version=“1.0?”>
- 注释:
- 属性:25000
- XML文件读取
- 创建文档文件
- 加载XML文档
- 获取根节点
- 遍历节点并封装数据