【问题标题】:How can I serialize a List<> of classes that I've created如何序列化我创建的类的 List<>
【发布时间】:2016-03-17 21:26:51
【问题描述】:

我有以下代码:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
    saveFileDialog.AddExtension = true;
    saveFileDialog.DefaultExt = ".xml";
    var resultDialog = saveFileDialog.ShowDialog(this);
    if (resultDialog == System.Windows.Forms.DialogResult.OK)
    {
        string fileName = saveFileDialog.FileName;
        SerializeObject(ListaDeBotoes, fileName);
    }
}

public void SerializeObject(List<MyButton> serializableObjects, string fileName)
{
    if (serializableObjects == null) { return; }

    try
    {
        XmlDocument xmlDocument = new XmlDocument();
        XmlSerializer serializer = new XmlSerializer(serializableObjects.GetType());
        using (MemoryStream stream = new MemoryStream())
        {
            serializer.Serialize(stream, serializableObjects);
            stream.Position = 0;
            xmlDocument.Load(stream);
            xmlDocument.Save(fileName);
            stream.Close();
        }
    }
    catch (Exception ex)
    {
        //Log exception here
    }
}

我的目标是保存MyButtons 的列表,这是我自己的课程(如果这件事它也是一个控件),我可以在将来重新打开它。但是这种方式行不通,它停在:XmlSerializer serializer = new XmlSerializer(serializableObjects.GetType()); 并且调用了 catch 异常......有什么建议吗?

【问题讨论】:

  • ...实际异常中的内容
  • “有什么建议吗?”你可能想看看 json.net;尽管有这个名字,我认为它 [de] 序列化 XML 以及 json。

标签: c# xml save xml-serialization


【解决方案1】:

试试这个....

用途.....

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

函数....

    private void Serialize<T>(T data)
    {

        // Use a file stream here.
        using (TextWriter WriteFileStream = new StreamWriter("test.xml"))
        {
            // Construct a SoapFormatter and use it  
            // to serialize the data to the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));

            try
            {
                // Serialize EmployeeList to the file stream
                SerializerObj.Serialize(WriteFileStream, data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }
        }
    }

    private T Deserialize<T>() where T : new()
    {
        //List<Employee> EmployeeList2 = new List<Employee>();
        // Create an instance of T
        T ReturnListOfT = CreateInstance<T>();


        // Create a new file stream for reading the XML file
        using (FileStream ReadFileStream = new FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Construct a XmlSerializer and use it  
            // to serialize the data from the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
            try
            {
                // Deserialize the hashtable from the file
                ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }

        }
        // return the Deserialized data.
        return ReturnListOfT;
    }

    // function to create instance of T
    public static T CreateInstance<T>() where T : new()
    {
        return (T)Activator.CreateInstance(typeof(T));
    }

用法....

Serialize(dObj); // dObj is List<YourClass>

List<YourClass> deserializedList = Deserialize<List<YourClass>>();

您的对象将被写入\读取到\来自一个名为 test.xml 的文件,您可以对其进行修改以适应...

希望对您有所帮助....

/////////////////////////////////////// ///////////////////////

为每个 MyButton 对象保存值的示例类可能如下所示......

public partial class PropertiesClass
{
    public string colorNow { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Black.ToArgb()));
    public string backgroundColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Black.ToArgb()));
    public string externalLineColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.DarkBlue.ToArgb()));
    public string firstColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Goldenrod.ToArgb()));
    public string secondColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.DarkGoldenrod.ToArgb()));
    public string mouseEnterColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.PaleGoldenrod.ToArgb()));
    public string doubleClickColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Gold.ToArgb()));

    public bool shouldIChangeTheColor { get; set; } = true;
    public bool selectedToMove { get; set; } = true;
    public bool selectedToLink { get; set; } = true;
}

用法...

        List<PropertiesClass> PropertiesClasses = new List<PropertiesClass>();
        PropertiesClass PropertiesClass = new PropertiesClass();
        PropertiesClasses.Add(PropertiesClass);
        Serialize(PropertiesClasses); 

【讨论】:

  • 好的,但是在XmlSerializer SerializerObj = new XmlSerializer(typeof(T)); 行中发生了异常There was an error reflecting type 'System.Collections.Generic.List'1[MyButtonCode.MyButton]'.。你知道发生了什么事吗?
  • 需要查看您传递给 XmlSerializer 的类(MyButton)
  • 在您的代码中(发布在问题中),您将 'List' 传递给 SerializeObject 函数。我需要查看“MyButton”的代码。请使用“MyButton”类的代码更新您的问题
  • 您不能序列化从 UserControl 继承的类。您需要定义描述控件 (MyButton) 所需属性的类,而不是序列化实际控件。然后,您可以在运行时通过从文件中读回值来设置每个 MyButton 的属性....
  • 我已经用一个示例类修改了我的答案,说明如何将每个 MyButton 对象的值序列化为 XML...
【解决方案2】:

如果那不是作业或学习内容,您最好使用Json.NET 来序列化您的课程。改造井可能会花费你更多的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多