C# 对象序列化三种方式
对象标记为可序列化,然后把不需要序列化的字段加上[NonSerialized]特性
序列化测试对象SerializeTest
[Serializable]
public class SerializeTest
{
[NonSerialized]
private string _name;
public SerializeTest(string name, string ip, int port, ITestInfo testInfo)
{
Name = name;
IP = ip;
Port = port;
TestInfo = testInfo;
}
public string Name { get { return _name; } set { _name = value; } }
public string IP { get; set; }
public int Port { get; set; }
public ITestInfo TestInfo { get; set; }
}
序列化对象包含的对象接口
public interface ITestInfo
{
string Message { get; set; }
int Id { get; set; }
List InfoList { get; set; }
}
序列化对象包含的对象接口实现
[Serializable]
public class TestInfo : ITestInfo
{
public TestInfo(string message, int id, List infoList)
{
Message = message;
Id = id;
InfoList = infoList;
}
public string Message { get; set; }
public int Id { get; set; }
public List InfoList { get; set; }
}
然后通过窗体的保存按钮进行对象序列化,加载时反序列化,进行测试,代码如下:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var serializeTest = SerializeUtils.DeserializeBinaryFromFile("F:\\temp\\test.dat");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ITestInfo testInfo = new TestInfo("消息",1,new List { "测试","121"});
SerializeTest serializeTest = new SerializeTest("序列化测试","127.0.0.1",8080,testInfo);
SerializeUtils.SerializeBinaryToFile(serializeTest, "F:\\temp\\test.dat");
}
}
序列化工具类
public class SerializeUtils
{
public static object DeserializeBinaryFromFile(string file)
{
FileStream fs = null;
try
{
fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);
BinaryFormatter deserializer = new BinaryFormatter();
object newobj = deserializer.Deserialize(fs);
fs.Close();
return newobj;
}
catch (Exception ex)
{
if (fs != null) fs.Close();
return null;
}
}
public static bool SerializeBinaryToFile(object request, string file)
{
try
{
BinaryFormatter serializer = new BinaryFormatter();
FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite);
serializer.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;
serializer.Serialize(fs, request);
fs.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
测试结果如下:
点击保存待保存对象截图:
重新启动反序列化结果如下:
Name为null,没有保存
通过实现ISerializable接口的GetObjectData方法,把需要序列化保存的数据通过info.AddValue方法进行添加,此时不需要使用特性 [NonSerialized]
添加有参构造来实现对象的数据的获取
将SerializeTest类改造如下
[Serializable]
public class SerializeTest : ISerializable
{
public SerializeTest(string name, string ip, int port, ITestInfo testInfo)
{
Name = name;
IP = ip;
Port = port;
TestInfo = testInfo;
}
public string Name { get; set; }
public string IP { get; set; }
public int Port { get; set; }
public ITestInfo TestInfo { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("IP", this.IP);
info.AddValue("Port", this.Port);
info.AddValue("TestInfo", this.TestInfo);
}
protected SerializeTest(SerializationInfo info, StreamingContext context)
{
try
{
SerializationInfoEnumerator enumerator = info.GetEnumerator();
this.IP = GetValueBySerializationInfo(info, "IP");
this.Port = GetValueBySerializationInfo(info, "Port");
while (enumerator.MoveNext())
{
if (enumerator.Name == "TestInfo") this.TestInfo = (ITestInfo)enumerator.Value;
}
}
catch (Exception e)
{
}
}
///
/// 根据key从序列化对象获取值
///
///
///
///
///
public T GetValueBySerializationInfo(SerializationInfo info, string key)
{
try
{
return (T)info.GetValue(key, typeof(T));
}
catch
{
return default(T);
}
}
}
删除test.dat文件重新测试,测试结果一致。
在方式二的基础上通过反射自动将需要序列化的数据进行保存和获取,注意此方式将不需要序列化的属性使用特性[XmlIgnore]标记,对于需要序列化的属性较多时效果较好,SerializeTest类改造如下:
[Serializable]
public class SerializeTest : ISerializable
{
public SerializeTest(string name, string ip, int port, ITestInfo testInfo)
{
Name = name;
IP = ip;
Port = port;
TestInfo = testInfo;
TestInfo = testInfo;
}
[XmlIgnore]
public string Name { get; set; }
public string IP { get; set; }
public int Port { get; set; }
public ITestInfo TestInfo { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
var properties = GetProperties();
foreach (var property in properties)
{
if (IsNeedSerializedProperty(property))
{
info.AddValue(property.Name, GetPropertyValue(property));
}
}
}
protected SerializeTest(SerializationInfo info, StreamingContext context)
{
try
{
var properties = GetProperties();
foreach (var property in properties)
{
if (IsNeedSerializedProperty(property))
{
try
{
SetPropertyValue(property, GetValueBySerializationInfo
删除test.dat文件重新测试,测试结果一致。