≪シーケンス化|Sequencing|oem_src≫:別のオブジェクトに逆シーケンス化


タイプPersonをファイルにシーケンス化すると、別のタイプPersonAnotherに逆シーケンス化されます.以下は関連コードです.
 
using System;
using System.Runtime.Serialization;

namespace ConsoleApp_SerializableToAnotherObj
{
class Program
{
static void Main(string[] args)
{
//
Person personA=new Person(){FirstName = "Zhang",LastName = "San"};
BinarySerializer.SerializeToFile(personA,@"c:\","person.txt");
PersonAnother p = BinarySerializer.DeserializeFromFile<PersonAnother>(@"
c:\person.txt");
Console.WriteLine(p.Name);
Console.ReadKey();
}
}

[Serializable]
class PersonAnother : ISerializable
{
public string Name { get; set; }

protected PersonAnother(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("
Name");
}

void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}
}

[Serializable]
class Person : ISerializable
{
public string FirstName;
public string LastName;
public string ChineseName;

public Person()
{
}
protected Person(SerializationInfo info, StreamingContext context)
{ }

void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(PersonAnother));
info.AddValue("
Name", string.Format("{0} {1}", LastName, FirstName));
}
}
}


ツールクラス:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp_SerializableToAnotherObj
{
public class BinarySerializer
{
/// <summary>
///
/// </summary>
public static string Serialize<T>(T t)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}

/// <summary>
///
/// </summary>
public static void SerializeToFile<T>(T t, string path, string fullname)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fullPath = string.Format(@"{0}\{1}", path, fullname);
using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
stream.Flush();
}
}

/// <summary>
///
/// </summary>
public static TResult Deserialize<TResult>(string s) where TResult : class
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(s);
using (MemoryStream stream = new MemoryStream(bs))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}

/// <summary>
///
/// </summary>
public static TResult DeserializeFromFile<TResult>(string path) where TResult : class
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
}
}