在 c# 中序列化的 php 的类似物

本文关键字:php 类似物 序列化 | 更新日期: 2023-09-27 18:36:00

C#中是否有任何方法,例如在php中序列化和取消序列化?

我需要它作为通过网络传输阵列的最佳方式。

在 c# 中序列化的 php 的类似物

下面是

使用基本System.Xml.Serialization序列化和反序列化类实例的示例。当然,你可以用它做更多的事情,比如使用属性来控制序列化程序的工作方式等。

如果你想使用JSON格式,那么你可以使用JavascriptSerializer,它非常相似或更好,但使用 JSON.Net 更好。

using System.Xml.Linq;
using System.Xml.Serialization;
static void Main()
{
    //create something silly to serialise:
    var thing = new MyThing(){Name="My thing", ID=0};
    thing.SubThings.Add(new MySubThing{ID=1});
    thing.SubThings.Add(new MySubThing{ID=2});

    //serialise to XML using an XDocument as the output 
    //(you can use any stream writer though)
    //first create the serialiser
    var serialiser = new XmlSerializer(typeof(MyThing));
    //then create an XDocument and get an XmlWriter from it
    var output= new XDocument();
    using(var writer = output.CreateWriter())
    {
       serialiser.Serialize(writer,thing);
    }
    Console.WriteLine(output.ToString());
    /*expected output:
     <MyThing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Name>My thing</Name>
      <ID>0</ID>
      <SubThings>
        <MySubThing>
          <ID>1</ID>
        </MySubThing>
        <MySubThing>
          <ID>2</ID>
        </MySubThing>
      </SubThings>
    </MyThing>
    */
    //Send across network
    //...
    //On other end of the connection, deserialise from XML.
    //Again using XDocument as the input
    //or any Stream Reader containing the data
    var source = output.ToString();
    var input = XDocument.Parse(source);
    MyThing newThing = null;
    using (var reader = input.CreateReader())
    {
      newThing = serialiser.Deserialize(reader) as MyThing;
    }
    if (newThing!=null)
    {
       Console.WriteLine("newThing.ID={0}, It has {1} Subthings",newThing.ID,newThing.SubThings.Count);
    }
    else
    {
        //something went wrong with the de-serialisation.
    }
}
//just some silly classes for the sample code.
public class MyThing
{
   public string Name{get;set;}
   public int ID{get;set;}
   public List<MySubThing> SubThings{get;set;}
   public MyThing()
   {
        SubThings=new List<MySubThing>();
   }
}
public class MySubThing
{
  public int ID{get;set;}
}

希望能让你指向正确的方向...

MS建议

: http://msdn.microsoft.com/en-us/library/vstudio/et91as27.aspx

你也可以使用这样的东西(这里是双精度的,但可以修改为任何数据类型):

序列 化:

 public string Serialize(double[] Source, string Separator)
    {
        string result = "";
        foreach (double d in Source) result += d.ToString()+Separator;
        return result;
    }

反序列化

public double[] UnSerialize(string Source, char[] separators)
{
    //splitting Source array by separators   "1|2|3" => Split by '|' => [1],[2],[3]
    string[] tmp = Source.Split(separators, StringSplitOptions.RemoveEmptyEntries);
    double[] result = new double[tmp.Length];
    for(int i=0;i<tmp.Length) {result[i]=Convert.ToDouble(tmp[i]);}
    return result;
}