gpt4 book ai didi

c# - 带有c#代码错误的序列化

转载 作者:太空宇宙 更新时间:2023-11-03 13:24:00 25 4
gpt4 key购买 nike

我正在尝试概括我的一个项目的序列化。

我有如下三个主要类:

test.cs - 一个简单的测试对象

[Serializable()]
public class test : Attribute {

public string name = "";
public int ID = 0;

public test(string inputName, int inputID) {
name = inputName;
ID = inputID;
}
public test() {}
}

Serialization.cs - 我的主要序列化类

public static void SerializeCollection<T>(string path, List<T> collection, Type type) {
System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(type);
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
writer.Serialize(file, collection);
}

最后是 Form1.cs - 我的表单类

    private void btnSerialize_Click(object sender, EventArgs e)
{
List<test> test = new List<test>();
test.Add(new test("testing1", 2));
Serialization.SerializeCollection("Test.txt", test, typeof(test));
}

当运行并点击按钮时,我得到这个错误:

'An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll

Additional information: There was an error generating the XML document.'

最佳答案

您使用了不正确的类型进行序列化,您已将 typeof(test) 更改为 typeof(List)

    private static void SerializationTest()
{
List<test> test = new List<test>();
test.Add(new test("testing1", 2));
SerializeCollection("Test.txt", test, typeof(List<test>));
}

老实说,在您的情况下,我会避免将类型作为方法的参数:

    private static void SerializationTest()
{
const string fileName = "Test.txt";
var tests = new List<test> {new test("testing1", 2)};
SerializeCollection(fileName, tests);
}

public static void SerializeCollection<T>(string fullFileName, IEnumerable<T> items)
{
var writer = new XmlSerializer(items.GetType());
var file = new StreamWriter(fullFileName);
writer.Serialize(file, items);
}

关于c# - 带有c#代码错误的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23091898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com