C#binaryformatter
时间: 2023-06-17 20:05:12 浏览: 52
C# BinaryFormatter 是一个用于序列化和反序列化 .NET 对象的类。它可以将对象转换为字节数组,以便在网络上传输或保存到文件中,也可以将字节数组转换回对象。
以下是一个简单的示例,演示如何使用 BinaryFormatter 将对象序列化为字节数组并将其保存到文件中:
```
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person { Name = "John", Age = 30 };
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, person);
byte[] bytes = stream.ToArray();
File.WriteAllBytes("person.dat", bytes);
}
}
```
在这个示例中,我们创建了一个名为 Person 的简单类,并使用 BinaryFormatter 将其序列化为字节数组。然后,我们使用 MemoryStream 将字节数组保存到内存中,并使用 File.WriteAllBytes 将其写入文件 "person.dat" 中。
反序列化对象的过程与序列化相反。以下是一个简单的示例,演示如何使用 BinaryFormatter 从文件中读取字节数组并将其反序列化为对象:
```
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
byte[] bytes = File.ReadAllBytes("person.dat");
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(bytes);
Person person = (Person)formatter.Deserialize(stream);
Console.WriteLine("Name: {0}", person.Name);
Console.WriteLine("Age: {0}", person.Age);
}
}
```
在这个示例中,我们使用 File.ReadAllBytes 从文件 "person.dat" 中读取字节数组。然后,我们使用 MemoryStream 将字节数组加载到内存中,并使用 BinaryFormatter 将其反序列化为 Person 对象。最后,我们输出 Person 对象的属性值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)