65.9K
CodeProject 正在变化。 阅读更多。
Home

将序列化构建到类中

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (5投票s)

2016年6月24日

CPOL

2分钟阅读

viewsIcon

11719

downloadIcon

134

为 C# 中的类添加内置序列化功能的代码。

引言

在一个最近的项目中,我需要保存和加载数据库应用程序使用的各种对象的状态。解决方案是在包含应用程序数据的类中添加序列化功能。

最初的解决方案是构建一个 Visual Studio 项目模板,该模板可以快速创建包含通过 XML 格式文件或 string 进行读取和写入类属性值的内置功能的类。

第二个解决方案是构建一个泛型类,该类将任何类类型作为参数,并提供相同的读取/写入 XML 功能。

两种解决方案都提供序列化到文件、string 和数据库表。每种类型的序列化都包含加密序列化值的相关方法。

Visual Studio 类模板

使用了 .NET XML 序列化命名空间来提供 XML 序列化/反序列化功能。

使用了 System.Reflection 命名空间来提供将对象的内容输出到非 XML 格式的 string 值的方法。

附带的源代码不包含任何二进制或 SOAP 序列化功能。

有关将自定义项目模板添加到“添加新项目”对话框中所需的步骤,请参阅以下链接:

//
// Selected Save and Load methods from the Visual Studio class template for classes 
// with built-in serialization
//

public class ClassTemplateWithSerializers
{
.....

/// <summary>
/// Saves the column definitions contained in the current instance to the specified file. 
/// Serialization is used for the save.
/// </summary>
/// <param name="filePath">Full path for output file.</param>

public void SaveToXmlFile(string filePath)
{
       XmlSerializer ser = new XmlSerializer(typeof(ClassTemplateWithSerializers));
       TextWriter tex = new StreamWriter(filePath);
       ser.Serialize(tex, this);
       tex.Close();
}

/// <summary>
/// Creates and initializes an instance of the class by loading a serialized version 
/// of the instance from a file.
/// </summary>
/// <param name="filePath">Full path for the input file.</param>
/// <returns>An instance of ClassTemplateWithSerializers.</returns>
public static ClassTemplateWithSerializers LoadFromXmlFile(string filePath)
{
       XmlSerializer deserializer = new XmlSerializer(typeof(ClassTemplateWithSerializers));
       TextReader textReader = new StreamReader(filePath);
       ClassTemplateWithSerializers columnDefinitions;
       columnDefinitions = (ClassTemplateWithSerializers)deserializer.Deserialize(textReader);
       textReader.Close();
       return columnDefinitions;
}

使用泛型的类管理器

如果您不想在每个类中重复序列化逻辑,可以使用 ClassManager 模块。该模块使用泛型来接受类类型的实例作为构造函数的参数。它的方法然后以泛型方式操作类实例。

//
// Selected Save and Load methods from the generic class manager.
//

public class ClassManager<T>
{
.....
/// <summary>
/// Saves the column definitions contained in the current instance to the specified file. 
/// Serialization is used for the save.
/// </summary>
/// <param name="filePath">Full path for output file.</param>
public void SaveToXmlFile(string filePath)
{
       XmlSerializer ser = new XmlSerializer(typeof(T));
       TextWriter tex = new StreamWriter(filePath);
       ser.Serialize(tex, _classInstance);
       tex.Close();
}

/// <summary>
/// Creates and initializes an instance of the class by loading a serialized version 
/// of the instance from a file.
/// </summary>
/// <param name="filePath">Full path for the input file.</param>
/// <returns>An instance of the object.</returns>
public static T LoadFromXmlFile(string filePath)
{
       XmlSerializer deserializer = new XmlSerializer(typeof(T));
       TextReader textReader = new StreamReader(filePath);
       T columnDefinitions;
       columnDefinitions = (T)deserializer.Deserialize(textReader);
       textReader.Close();
       return columnDefinitions;
}

Using the Code

//
// Examples that demonstrate the use of class instances derived from the Visual Studio template.
//

private static ClassWithSerializers _classWithSerializers = new ClassWithSerializers();
…..
classWithSerializers.IntValue = 25321;
…...
// Save class instance
_classWithSerializers.SaveToXmlFile(outputPath);
…..
//Retrieve saved instance into a new instance
ClassWithSerializers newObject = new ClassWithSerializers();
newObject = ClassWithSerializers.LoadFromXmlFile(outputPath);
//
// Examples that demonstrate the use of the Class Manager to display the contents
// of an object instance that does not have built-in serialization.
//

private static ClassManager<TestClassNoSerializers> _classManager;
.....
//Save object to an XML file
_classManager.SaveToXmlFile(outputPath);
 ....
//Load object from instance saved in XML file
_classManager.SaveToXmlFile(outputPath);
newObject2 = ClassManager<TestClassNoSerializers>.LoadFromXmlFile(outputPath);
ClassManager<TestClassNoSerializers> clsmgr2 = new ClassManager<TestClassNoSerializers>(newObject2);
outputString = clsmgr2.ToXmlString();
.....

关注点

此代码仅使用 XML 序列化。采用这种方法是为了帮助排查任何应用程序问题。

在需要安全性的情况下,在类模板和泛型类管理器中都包含了使用 AES 加密进行序列化的方法。

通过构建使用 .NET 提供的 System.Data.Odbc 功能的方法来编码保存到数据库。在实际场景中,您可以修改此代码以使用另一个 .NET 数据库提供程序。

历史

这是代码的首次公开发布。

© . All rights reserved.