2014-04-15 40 views
2

我想推廣我的一個項目的序列化。序列化與C#代碼錯誤

我有三個主要類別如下:

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.' 
+4

是否有內部異常?如果是這樣,那麼它的信息是什麼? – Aybe

回答

1

您使用不正確類型的序列化,你有改變的typeof(測試)來的typeof(名單)

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); 
    } 
+0

謝謝你,我改變了位置,我把類型引用到'collection.getType()',現在它工作:) – MAWood