using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization; namespace 序列化
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Person p = new Person();
p.Name ="张三";
p.Age =;
p.Gender = true; using (System.IO.FileStream file = new FileStream("person.dat", FileMode.Create, FileAccess.Write))
{
//System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter b = new BinaryFormatter();
b.Serialize(file, p); //序列化
}
MessageBox.Show("ok");
} private void button2_Click(object sender, EventArgs e)
{
using (System.IO.FileStream file = new FileStream("person.dat", FileMode.Open, FileAccess.Read))
{
BinaryFormatter b = new BinaryFormatter();
Person p = (Person)b.Deserialize(file); //反序列化 MessageBox.Show(p.Name);
}
} private void button3_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
Person p = new Person();
p.Name = "张三";
p.Age = ;
p.Gender = true;
Person p2 = new Person();
p2.Name = "李四";
p2.Age = ;
p2.Gender = true; list.Add(p);
list.Add(p2); //将Person类对象序列化写入流中
using (System.IO.FileStream file = File.OpenWrite("person.xml"))
{
//System.Xml.Serialization;
XmlSerializer xmlSer = new XmlSerializer(typeof(Person));
xmlSer.Serialize(file, p);
} //也可以将List集合对象序列化写入到流中,对象是Object类型。
using (System.IO.FileStream file = File.OpenWrite("personList.xml"))
{
XmlSerializer xmlSer = new XmlSerializer(typeof(List<Person>)); //通过反射指定类型
xmlSer.Serialize(file, list);
} MessageBox.Show("ok");
} private void button4_Click(object sender, EventArgs e)
{
//Xml反序列化
using (System.IO.FileStream file = File.OpenRead("person.xml"))
{
XmlSerializer xmlSer = new XmlSerializer(typeof(Person));
Person p = (Person)xmlSer.Deserialize(file);
MessageBox.Show(p.Name);
}
}
}
//程序集“序列化, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类型“序列化.Person”未标记为可序列化。
[Serializable] //Serializable 可以被序列化,此类不能被继承。 //XML序列化中不需要此方法!
public class Person
{
private string name;
private int age;
private bool gender; [XmlIgnore] //XmlIgnoreAttribute 不序列化公共字段或公共读写属性值。
public bool Gender
{
get { return gender; }
set { gender = value; }
} public int Age
{
get { return age; }
set { age = value; }
} public string Name
{
get { return name; }
set { name = value; }
} }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization; namespace 序列化
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
MyPerson mp = new MyPerson();
mp.Name = "张三";
mp.Age = ;
mp.Gender = true; using (System.IO.FileStream file = new System.IO.FileStream("myPerson.xml", System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
//创建自己写的序列化类对象
MyXmlSerializer myXmlSer = new MyXmlSerializer();
//调用序列化方法,保存到文件中。
myXmlSer.Serialize(file, mp);
}
MessageBox.Show("ok");
}
} public class MyPerson
{
private string name;
private int age;
private bool gender; [MyXmlIgnore] //添加特性,这个公有的属性将不被序列化,在序列化方法里实现。
public bool Gender
{
get { return gender; }
set { gender = value; }
} public int Age
{
get { return age; }
set { age = value; }
} public string Name
{
get { return name; }
set { name = value; }
} }
//模拟写一个序列化方法类
public class MyXmlSerializer
{
/// <summary>
/// 使用指定的 System.IO.Stream 序列化指定的 System.Object 并将 XML 文档写入文件。
/// </summary>
/// <param name="stream">用于编写 XML 文档的 System.IO.Stream。</param>
/// <param name="o">将要序列化的 System.Object。</param>
public void Serialize(System.IO.Stream stream, object o)
{
//通过反射获取对象类型
Type typeObj = o.GetType(); //创建XML文档
System.Xml.Linq.XDocument xdoc = new System.Xml.Linq.XDocument();
//创建XML元素,获取对象类型类名称作为,XML根节点名称
System.Xml.Linq.XElement xRoot = new System.Xml.Linq.XElement(typeObj.Name);
//添加到XML根节点
xdoc.Add(xRoot); //通过反射获取这个类型的所有公共属性
System.Reflection.PropertyInfo[] pinfos = typeObj.GetProperties(); //遍历pinfos每个属性都有创建XML元素
foreach (System.Reflection.PropertyInfo info in pinfos)
{
//通过每个属性获取它的特性,判断有没有MyXmlIgnoreAttribute特性,如果没有才给序列化。
object[] objAttrs = info.GetCustomAttributes(typeof(MyXmlIgnoreAttribute), false);
//当小于等于0时,可判定该属性没有MyXmlIgnoreAttribute特性,可以被序列化。
if (objAttrs.Length <= )
{
System.Xml.Linq.XElement xelet = new System.Xml.Linq.XElement(info.Name, info.GetValue(o));
xRoot.Add(xelet); //添加到根节点下面
}
//有MyXmlIgnoreAttribute特性的就不写入XML。
}
//保存XML到流中去
xdoc.Save(stream);
}
} //不序列化属性字段特性
public class MyXmlIgnoreAttribute : Attribute
{ }
}

关于反序列化:

<?xml version="1.0"?>
<PersonRoot>
  <Person>
    <Age>18</Age>
    <Name>张三</Name>
  </Person>
  <Person>
    <Age>19</Age>
    <Name>李四</Name>
  </Person>
</PersonRoot>

public class PersonRoot
{
List<Person> perList = new List<Person>(); [XmlElement(ElementName = "Person")]
public List<Person> PerList
{
get { return perList; }
set { perList = value; }
}
}
using (System.IO.FileStream file = File.OpenRead("personList.xml"))
{
XmlSerializer xmlSer = new XmlSerializer(typeof(PersonRoot));
PersonRoot list = (PersonRoot)xmlSer.Deserialize(file);
MessageBox.Show(list.PerList[].Name);
}

XML数据格式,

<ArrayOfPerson>

<Person>

可以直接List<Person>类型反序列化到List<Person>对象中。

Attribute:

Attribute 类将预定义的系统信息或用户定义的自定义信息与目标元素相关联。 目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、可移植可执行文件模块、参数、属性、返回值、结构或其他特性。

特性所提供的信息也称为元数据。 元数据可由应用程序在运行时进行检查以控制程序处理数据的方式,也可以由外部工具在运行前检查以控制应用程序处理或维护自身的方式。 例如,.NET Framework 预定义特性类型并使用特性类型控制运行时行为,某些编程语言使用特性类型表示 .NET Framework 常规类型系统不直接支持的语言功能。

所有特性类型都直接或间接地从 Attribute 类派生。 特性可应用于任何目标元素;多个特性可应用于同一目标元素;并且特性可由从目标元素派生的元素继承。 使用 AttributeTargets 类可以指定特性所应用到的目标元素。

Attribute 类提供检索和测试自定义特性的简便方法。 有关使用特性的更多信息,请参见 应用特性利用特性扩展元数据

下面的代码示例演示 Attribute 的用法。

using System;
using System.Reflection; // An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal {
// Pets.
Dog = ,
Cat,
Bird,
} // A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute {
// The constructor is called when the attribute is set.
public AnimalTypeAttribute(Animal pet) {
thePet = pet;
} // Keep a variable internally ...
protected Animal thePet; // .. and show a copy to the outside world.
public Animal Pet {
get { return thePet; }
set { thePet = value; }
}
} // A test class where each method has its own pet.
class AnimalTypeTestClass {
[AnimalType(Animal.Dog)]
public void DogMethod() {} [AnimalType(Animal.Cat)]
public void CatMethod() {} [AnimalType(Animal.Bird)]
public void BirdMethod() {}
} class DemoClass {
static void Main(string[] args) {
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
// Iterate through all the methods of the class.
foreach(MethodInfo mInfo in type.GetMethods()) {
// Iterate through all the Attributes for each method.
foreach (Attribute attr in
Attribute.GetCustomAttributes(mInfo)) {
// Check for the AnimalType attribute.
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine(
"Method {0} has a pet {1} attribute.",
mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
} }
}
}
/*
* Output:
* Method DogMethod has a pet Dog attribute.
* Method CatMethod has a pet Cat attribute.
* Method BirdMethod has a pet Bird attribute.
*/

C# 二进制序列化(BinaryFormatter),Xml序列化(XmlSerializer),自己模拟写一个Xml序列化过程。的更多相关文章

  1. 写一个xml文件到磁盘的方法

    /** * 往磁盘上写一个xml文件 * * <?xml version="1.0" encoding="UTF-8" standalone=" ...

  2. 一个可序列化的C#对象,如何转成一个XML格式的文件或字符串【转】

    原文:http://blog.csdn.net/otong/article/details/7894059 序列化或反序列化成一个字符串: 方法一: 序列化: public static string ...

  3. 把xml格式的字符串写入到一个xml文件中

    package demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; impo ...

  4. 通常一个 Xml 映射文件,都会写一个 Dao 接口与之对应, 请问,这个 Dao 接口的工作原理是什么?Dao 接口里的方法, 参数不同时,方法能重载吗?

    Dao 接口即 Mapper 接口.接口的全限名,就是映射文件中的 namespace 的值: 接口的方法名,就是映射文件中 Mapper 的 Statement 的 id 值:接口方法内的 参数,就 ...

  5. 通常一个Xml映射文件,都会写一个Dao接口与之对应,请问,这个Dao接口的工作原理是什么?Dao接口里的方法,参数不同时,方法能重载吗?

    Dao接口即Mapper接口.接口的全限名,就是映射文件中的namespace的值:接口的方法名,就是映射文件中Mapper的Statement的id值:接口方法内的参数,就是传递给sql的参数. M ...

  6. testng入门教程16数据驱动(把数据写在xml)

    testng入门教程16数据驱动(把数据写在xml) testng入门教程16数据驱动(把数据写在xml)把数据写在xml文件里面,在xml文件右键选择runas---testng执行 下面是case ...

  7. c# 序列化BinaryFormatter、SoapFormatter和XmlSerializer的区别

    在C#中常见的序列化的方法主要也有三个:BinaryFormatter.SoapFormatter.XML序列化 1.BinaryFormatter 序列化 [Serializable] //如果要想 ...

  8. C#操作Xml:XmlSerializer 对象的Xml序列化和反序列化

    这篇随笔对应的.Net命名空间是System.Xml.Serialization:文中的示例代码需要引用这个命名空间. 为什么要做序列化和反序列化? .Net程序执行时,对象都驻留在内存中:内存中的对 ...

  9. wcf中序列化BinaryFormatter,DataContractJsonSerializer,DataContractSerializer,SoapFormatter,XmlSerializer

    using System; using System.Runtime.Serialization; using System.Xml.Serialization; namespace Larryle. ...

随机推荐

  1. 矩阵中的路径 剑指offer65题

    include "stdafx.h" #include<vector> #include<algorithm> #include<string> ...

  2. NDK 安装小结

    建议先看后面的错误,可以先执行那些命令以免出现相关问题. chmod a+x android-ndk-r10c-linux-x86_64.bin ./android-ndk-r10c-linux-x8 ...

  3. JavaScript 测试和捕捉

    try 语句允许我们定义在执行时进行错误测试的代码块. catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块. JavaScript 语句 try 和 catch 是成对出现的.

  4. ORACL EXP导出数据说明

    转载自:http://www.jb51.net/article/17358.htm Oracle 数据库导出(exp)导入(imp)说明   exp 将数据库内的各对象以二进制方式下载成dmp文件,方 ...

  5. ASP.NET动态网站制作(26)-- Ajax

    前言:这节课讲解关于Ajax的相关内容. 内容: 1.当点击页面中的一个按钮提交数据或请求数据的时候,整个页面的信息都会提交(不管信息是否是提交或者请求的数据,页面中所有的数据都提交),这样耗用的时间 ...

  6. WebApi~通过HttpClient来调用Web Api接口

    异步请求 ///<summary> /// HttpClient实现Post请求(异步) /// </summary> static async void dooPost() ...

  7. 提高打开Android本地文档的速度

    非常多Android开发人员在參考Android官方API时,都有一个令人头疼的问题:打开一个index.html平均都须要几分钟甚至更长.尤其是在打开API 8以上的版本号的时候.难道是网速不够好? ...

  8. IDLE崩溃:IDLE's subprocess didn't make connection. Either IDLE can't start a...

    今天在测试Python脚本的时候,突然间发现,脚本不能启动了,还弹出了“IDLE's subprocess didn't make connection. Either IDLE can't star ...

  9. conda 和 pip 安装,更新,删除

    安装: pip install xxx conda install xxx 更新: pip  install --upgrade xxx conda update xxx 删除: pip uninst ...

  10. L - Points on Cycle(旋转公式)

    L - Points on Cycle Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u ...