在C#中可以使用php中的序列化和反序列化等任何方法吗?
我需要它以通过网络传输阵列的最佳方式。
答案 0 :(得分:1)
你也可以使用这样的东西(这里是双打,但可以修改为任何数据类型):
序列化:
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;
}
答案 1 :(得分:1)
以下是使用基本System.Xml.Serialization
序列化和反序列化类实例的示例。当然,您可以使用attributes来控制序列化程序的工作方式,等等。
如果您想使用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;}
}
希望能让你指出正确的方向......