using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"{Name} is {Age} years old.";
}
}
public class Program
{
public static void Main()
{
// 反序列化示例
string filePath = "person.dat";
if (File.Exists(filePath))
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
Person deserializedPerson = (Person)formatter.Deserialize(fs);
Console.WriteLine("Deserialized Person: " + deserializedPerson);
}
}
else
{
Console.WriteLine("File does not exist.");
}
}
}
Person
类,包含两个属性 Name
和 Age
,以及一个重写的 ToString
方法。Main
方法中,我们尝试从文件 person.dat
中读取并反序列化一个 Person
对象。BinaryFormatter
进行反序列化。需要注意的是,BinaryFormatter
已经被标记为不安全,建议在生产环境中使用更安全的替代方案,如 System.Text.Json
或 Newtonsoft.Json
。请注意,BinaryFormatter
已经被标记为不安全,建议在生产环境中使用更安全的替代方案。
上一篇:c# 字节数组转字符串
下一篇:c# tostring有效位数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站