如何序列化我创建的 类 的列表<>

How can I serialize a List<> of classes that I've created

我有以下代码:

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

我的 objective 是保存这个 MyButton 的列表,那是我自己的 class (如果这很重要,它也是一个控件),以我可以的方式以后再开吧。但是这种方式不起作用它停在:XmlSerializer serializer = new XmlSerializer(serializableObjects.GetType()); 并且调用了 catch 异常......有什么建议吗?

如果那不是家庭作业或学习资料,您最好使用 Json.NET 来连载您的 类。重新发明水井可能会花费您更多时间。

试试这个....

使用.....

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

您的对象将是 written\read to\from 一个名为 test.xml 的文件,您可以对其进行修改以适应....

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

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

保存每个 MyButton 对象的值的示例 class 可能看起来像这样......

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