C# 尝试将 ArrayList 序列化为 XML 文件

本文关键字:XML 文件 序列化 ArrayList | 更新日期: 2023-09-27 18:32:10

struct ClientInfo
    {
        public string strName;  //Name by which the user logged into the chat room
        public string strPW;
    }
    ArrayList clientList = new ArrayList();
    public static void Serialize(ArrayList input)
    {
        XmlSerializer serializer = new XmlSerializer(input.GetType());
        TextWriter sw = new StreamWriter("users.txt");
        serializer.Serialize(sw, input);
        sw.Close();
    }

所以我正在尝试将名称/密码组合存储在 ArrayList 中,并且我正在尝试将此 ArrayList 保存到一个文件中,并在每次程序启动时加载它。但是,程序在serializer.Serialize(sw, input);行停止,如下所示:

System.XML 中发生类型为"System.InvalidOperationException"的未处理异常.dll

我做错了什么?

C# 尝试将 ArrayList 序列化为 XML 文件

我们开始了;我认为这几乎解决了所有问题...

public class ClientInfo // you meant "class" right? since that clearly isn't a "value"
{
    public string Name {get;set;} // use a property; don't use a name prefix
    public string Password {get;set;} // please tell me you aren't storing passwords
}
List<ClientInfo> clientList = new List<ClientInfo>(); // typed list
public static void Serialize(List<ClientInfo> input) // typed list
{
    if(input == null) throw new ArgumentNullException("input");
    XmlSerializer serializer = new XmlSerializer(typeof(List<ClientInfo>));
    using(TextWriter sw = new StreamWriter("users.txt")) // because: IDisposable
    {
        serializer.Serialize(sw, input);
        sw.Close();
    }
}