如何序列化List<>我创建的课程

时间:2016-03-17 21:26:52

标签: c# xml save xml-serialization

我有以下代码:

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
    }
}

我的目标是保存这个MyButton的列表,这是我自己的类(如果这个问题,它也是一个控件),以一种我可以在未来重新打开它的方式。但这种方式不起作用它停在:XmlSerializer serializer = new XmlSerializer(serializableObjects.GetType());并且调用catch异常...任何建议?

2 个答案:

答案 0 :(得分:1)

试试这个......

Usings .....

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); 

答案 1 :(得分:0)

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