Wpf 任意类型的序列化

WPF对象序列化实战指南
本文详细介绍了如何在WPF应用中实现任意类型对象的序列化与反序列化,涵盖了XML、JSON等多种格式,包括关键步骤、示例代码及注意事项,帮助开发者高效管理应用程序的状态和数据。
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}";
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值