序列化、反序列化的使用_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 序列化、反序列化的使用

序列化、反序列化的使用

 2014/4/11 2:46:28  v.e.n.u.s  博客园  我要评论(0)
  • 摘要:调用:usingSystem;namespaceConsoleApp_Serializable{classProgram{staticvoidMain(string[]args){Personmike=newPerson(){Age=21,Name="Mike"};mike.NameChanged+=mike_NameChanged;BinarySerializer.SerializeToFile(mike,@"c:\","person.txt")
  • 标签:使用 序列化

调用:

monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">using System;

namespace ConsoleApp_Serializable
{
class Program
{
static void Main(string[] args)
{
Person mike = new Person() { Age = 21, Name = "Mike" };
mike.NameChanged += mike_NameChanged;
BinarySerializer.SerializeToFile(mike, @"c:\", "person.txt");
Person p = BinarySerializer.DeserializeFromFile<Person>(@"
c:\person.txt");
p.Name = "
rose";
Console.WriteLine(p.Name);
Console.WriteLine(p.Age.ToString());
Console.ReadKey();
}

static void mike_NameChanged(object sender, EventArgs e)
{
Console.WriteLine("
Name Changed !");
}
}

[Serializable]
class Person
{
private string name;
public int Age { get; set; }

public string Name
{
get { return name; }
set
{
if (NameChanged != null)
{
NameChanged(this, null);
}
name = value;
}
}

//事件往往是不需要序列化的,反序列化的环境和序列化的环境往往不一致,这就失去了将事件序列化的意义
[field: NonSerialized]
public event EventHandler NameChanged;
}
}
工具类:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp_Serializable
{
public class BinarySerializer
{
/// <summary>
/// 将类型序列化为字符串
/// </summary>
public static string Serialize<T>(T t)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}

/// <summary>
/// 将类型序列化为文件
/// </summary>
public static void SerializeToFile<T>(T t, string path, string fullname)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fullPath = string.Format(@"{0}\{1}", path, fullname);
using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
stream.Flush();
}
}

/// <summary>
/// 将字符串反序列化为类型
/// </summary>
public static TResult Deserialize<TResult>(string s) where TResult : class
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(s);
using (MemoryStream stream = new MemoryStream(bs))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}

/// <summary>
/// 将文件反序列化为类型
/// </summary>
public static TResult DeserializeFromFile<TResult>(string path) where TResult : class
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
}
}


发表评论
用户名: 匿名