zoukankan      html  css  js  c++  java
  • 【转】序列化与反序列化

    序列化与反序列化,当对象用来传输

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.IO;

    namespace CodeArt.SharePoint
    {
    /// <summary>
    /// 对象序列化
    /// </summary>
    public static class SerializeUtil
    {
    /// <summary>
    /// 将对象序列化成xml
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string Seralize(object obj)
    {
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(obj.GetType());

    MemoryStream s = new MemoryStream();
    XmlTextWriter w = new XmlTextWriter(s, Encoding.UTF8);

    //xs.Serialize(w, o, ns);

    xs.Serialize(w, obj);

    string xmlData = Encoding.UTF8.GetString(s.ToArray()).Trim();

    return xmlData;
    }

    /// <summary>
    /// 将xml反序列化成某个对象
    /// </summary>
    /// <param name="t"></param>
    /// <param name="xml"></param>
    /// <returns></returns>
    public static object Deserialize(Type t, string xml)
    {
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer( t );

    System.IO.StringReader sw = new System.IO.StringReader(xml);

    return xs.Deserialize(sw) ;
    }
    }
    }

    当一个类的信息要用来传输,只需要在类的顶部加上[Serialize],那么这个类就可以序列化了,并且可以用在页面传值

  • 相关阅读:
    AWK
    正则表达式
    BASH
    C# 常用控件的一些属性及方法
    C# FTP
    C# Delegate
    DLL/EXE查看工具Dumpbin
    VBA 破解Excel工作表保护密码
    VB6 IP地址+网卡地址+网卡类型
    编程之路┊由C#风潮想起的——给初学编程者的忠告 ZT
  • 原文地址:https://www.cnblogs.com/gzh4455/p/2438201.html
Copyright © 2011-2022 走看看