2009-12-02 64 views
1

系列化派生類我有這樣的代碼:問題在C#

[Serializable] 
public class A { 
    public int X { get; set; } 
} 
[Serializable] 
public class B : A{   
} 
[Serializable] 
public class C { 
    public A A { get; set; } 
} 
... 
    public string Serialize<T>(T obj) 
    { 
     StringBuilder stringBuilder = new StringBuilder(); 
     TextWriter stringWriter = new StringWriter(stringBuilder); 
     XmlWriter xmlWriter = new XmlTextWriter(stringWriter); 
     XmlSerializer serializer = new XmlSerializer(typeof(T)); 
     serializer.Serialize(xmlWriter, obj); 
     xmlWriter.Close(); 
     stringWriter.Close(); 
     return stringBuilder.ToString(); 
    } 

    private void Run() { 
     C c = new C() {A = new B()}; 
     string str = Serialize(c); 
    }  

我在文字"There was an error generating the XML document."

string str = SerializationManager.Serialize(c);執行我該怎麼寫我的代碼序列化c無一例外System.InvalidOperationException

回答

7

你需要告訴它繼承:

[XmlInclude(typeof(B)] 
public class A { 
    public int X { get; set; } 
} 
public class B : A{   
} 

請注意,您需要[Serializable]XmlSerializer

此外 - 看看內部異常:

try { ... } 
catch (Exception ex) { 
    while(ex != null) { 
     Console.WriteLine(ex.Message); 
     ex = ex.InnerException; 
    } 
} 

要看到:

「是沒有預料到的B型使用XmlInclude或SoapInclude屬性來指定不是靜態已知類型。 「。