鑑於此代碼DataContractSerializer與抽象(基礎)/具體(繼承)類
public override void Serialize(BaseContentObject obj)
{
string file = ObjectDataStoreFolder + obj.Slug + ".xml";
if(obj.GetType() == typeof(Page))
{
DataContractSerializer dcs = new DataContractSerializer(typeof Page));
XmlDictionaryWriter myWriter =
XmlDictionaryWriter.CreateTextWriter(new FileStream(file, ileMode.CreateNew, FileAccess.Write),
Encoding.UTF8);
dcs.WriteObject(myWriter, obj);
myWriter.Close();
}
else if(obj.GetType() == typeof(Image))
{
DataContractSerializer dcs = new DataContractSerializer(typeof Image));
...
...
}
}
有沒有辦法做這樣的事情
DataContractSerializer dcs = new DataContractSerializer(obj.GetType());
// this fails however, compiler error
並擺脫上面那些if()語句? DataContractSerializer的構造函數需要Type或Namespace,但它不能與obj.GetType()一起使用。
我的類層次結構如下:
BaseContentClass(abstract)
Page(具體,繼承BaseContentClass)
圖像(具體,繼承BaseContentClass)
...
?
我剛剛在其他地方再次嘗試過,它確實有效,所以我真的不明白它是從哪裏來的。謝謝! – mare 2010-01-13 12:46:27