c#中SOAP序列化和反序列化

c#中SOAP序列化和反序列化

上代码!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;//记得引用dll 和他的空间名滴呀; 
namespace SerlizeSoap
{
    [Serializable]
    public class Person
    {
        private string _name;
        private bool _sex;

        public Person(string name, bool sex)
        {
            this._name = name;
            this._sex = sex;
        }

        public override string ToString()
        {
            return "姓名:" + this._name + " 性别:" + (this._sex ? "男" : "女");
        }
    }
    [Serializable]
    public class Programmer : Person
    {
        private string _language;
        public Programmer(string name, bool sex, string lan)
            : base(name, sex)
        {
            this._language = lan;
        }

        public override string ToString()
        {
            return base.ToString() + "\t编程语言" + this._language;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Programmer p = new Programmer("Jack",true,"c#");
            //使用soap序列化对象;
            string fileName = @"d:\programmer.xml";
            Stream fStream = new FileStream(fileName,FileMode.Create,FileAccess.ReadWrite);
            SoapFormatter soapFormat = new SoapFormatter();
            soapFormat.Serialize(fStream,p);

            //然后我们再反序列化滴呀;
            fStream.Position = 0;
            p = null;
            p = (Programmer)soapFormat.Deserialize(fStream);
            fStream.Close(); //释放非托管资源;
            Console.WriteLine(p);
            Console.ReadLine();
        }
    }
}

总结:

SOAP序列化与二进制序列化的区别是:SOAP序列化不能序列化泛型类型。