[英]Serialization with c# code error
我正在嘗試概括我的一個項目的序列化。
我有以下三個主要課程:
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>));
}
老實說,在這種情況下,我會避免將type作為您的方法的參數:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.