C#如何反序列化多个对象
发布网友
发布时间:2024-10-05 10:05
我来回答
共2个回答
热心网友
时间:2024-11-14 05:13
你可以通过将两个值类型封装成对象的属性,并标记该对象为可序列化的,然后对该对象的集合进行序列化,然后取的时候反序列化该对象集合,这样不是更方便吗.
热心网友
时间:2024-11-14 05:13
没什么好说的,写个例子给你看吧,有些代码用了VS2008的特性,如果你用的是VS2008以下的版本,自己改下吧。
using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace Demo
{
public class Account
{
public int UserID
public string Username
}
class Program
{
static void Main( string[] args )
{
Account[] accounts = {
new Account(),
new Account(),
new Account()
};
string savePath = @"c:\XmlSerializerTest.txt";
XmlSerializer xs = new XmlSerializer( typeof( Account[] ) );
using ( TextWriter tw = new StreamWriter( savePath ) )
{
xs.Serialize( tw, accounts );
tw.Close();
using ( TextReader tr = new StreamReader( savePath ) )
{
Account[] deSerializedValue = xs.Deserialize( tr ) as Account[];
if ( deSerializedValue != null && deSerializedValue.Length > 0 )
{
for ( int i = 0; i < deSerializedValue.Length; i++ )
{
Console.WriteLine( "\tUserID = , Username = ", i, deSerializedValue[ i ].UserID, deSerializedValue[ i ].Username );
}
}
}
}
Console.ReadKey();
}
}
}
//----------二进制方式,可以使用BinaryFormatter 类来以二进制格式将对象或整个连接对象图形序列化和反序列化
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Demo
{
[Serializable]
public class Account
{
public int UserID
public string Username
}
class Program
{
static void Main( string[] args )
{
Account[] accounts = {
new Account(),
new Account(),
new Account()
};
string savePath = @"c:\BinarySerializerTest.bin";
BinaryFormatter formatter = new BinaryFormatter();
using ( FileStream writeStream = new FileStream( savePath, FileMode.Create, FileAccess.Write ) )
{
formatter.Serialize( writeStream, accounts );
//xs.Serialize( tw, accounts );
writeStream.Close();
using ( FileStream readStream = new FileStream( savePath, FileMode.Open, FileAccess.Read ) )
{
Account[] deSerializedValue = formatter.Deserialize( readStream ) as Account[];
if ( deSerializedValue != null && deSerializedValue.Length > 0 )
{
for ( int i = 0; i < deSerializedValue.Length; i++ )
{
Console.WriteLine( "\tUserID = , Username = ", i, deSerializedValue[ i ].UserID, deSerializedValue[ i ].Username );
}
}
}
}
Console.ReadKey();
}
}
}