2012-04-19 27 views
0

我有一個基類StandardMeasurement和派生類CustomMeasurement這兩個都可以序列化。將子類轉換爲XML序列化的基類?

這是我想做的事:從文件

  1. 加載一個CustomMeasurementcustomMeasInstance
  2. 創建新的std。 MEAS。 s.t .: StandardMeasurement stdMeas = (StandardMeasurement)customMeasInstance
  3. 序列號stdMeas(僅)作爲StandardMeasurement類型。

嘗試時出現錯誤,因爲stdMeas仍被XML序列化程序認爲是CustomMeasurement。有沒有辦法做到這一點,或者我必須手動「複製」所有信息?

謝謝!

+0

兼容性'我得到一個error'這是什麼錯誤? – 2012-04-19 21:06:17

回答

1

使用System.Xml.Serialization.XmlSerializer類,你應該能夠做這樣的事情:

編輯 -刪除object initializer與.NET 2.0

var cust = new CustomMeasurement(); 

cust.SomeProperty = "Foo"; 
cust.AnotherProperty = "Bar"; 

var serializer = new XmlSerializer(typeof(StandardMeasurement), new Type[] { cust.GetType() }); 
serializer.Serialize(Console.Out, cust); 
+0

好吧,我使用.NET 2.0,所以我不能嘗試:\但我嘗試添加'XmlInclude(typeof(CustomMeasurement))'屬性到我的'StandardMeasurement'類。它現在序列化,但包含我不想要的子屬性。思考? – john 2012-04-19 21:33:07

+0

也可以在.NET 2.0中使用'XmlSerializer'類。 「對象初始值設定項」直到3.5纔出現,但您可以用傳統方式初始化對象並設置屬性。 – 2012-04-19 21:44:01