在 C# 中有可用的任何方法,如 php 中的序列化和反序列化?
我需要它作为通过网络传输阵列的最佳方式。
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;
}
这是一个使用 basicSystem.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;}
}
希望这能让你指出正确的方向......