using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
ObservableCollection<Person> people = new ObservableCollection<Person>();
public MainWindow()
{
InitializeComponent();
myListBox.ItemsSource = people;
people.Add(new Person("AAABB", "CCCDDD"));
people.Add(new Person("A", "ds"));
people.Add(new Person("s", "S"));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SerializeToMemory(people);
MessageBox.Show("OK");
people.Clear();
}
private FileStream SerializeToMemory(Object objects)
{
using (
FileStream stream = new FileStream("collections.bin", FileMode.OpenOrCreate, FileAccess.Write)
){
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, objects);
return stream;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
people = (ObservableCollection<Person>)DeserilizedFromFile("collections.bin");
myListBox.ItemsSource = people;
}
private object DeserilizedFromFile(string filename)
{
using (
FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(file);
}
}
}
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string f, string l)
{
this.FirstName = f;this.LastName = l;
}
public override string ToString()
{
return $"{FirstName} {LastName}";
}
}
}
Wpf 任意类型的序列化
WPF对象序列化实战指南
最新推荐文章于 2024-09-03 13:03:39 发布
本文详细介绍了如何在WPF应用中实现任意类型对象的序列化与反序列化,涵盖了XML、JSON等多种格式,包括关键步骤、示例代码及注意事项,帮助开发者高效管理应用程序的状态和数据。
3019

被折叠的 条评论
为什么被折叠?



