2010-01-13 57 views
1

鑑於此代碼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)

...

回答

0

如果你在談論這個DataContractSerializer然後將下面的代碼將罰款編譯。

+0

我剛剛在其他地方再次嘗試過,它確實有效,所以我真的不明白它是從哪裏來的。謝謝! – mare 2010-01-13 12:46:27

3

告訴串行預見什麼:

[KnownType(typeof(Page))] 
[KnownType(typeof(Image))] 
[DataContract] 
public abstract class BaseContentObject { /* ... */ } 

[DataContract] 
public class Page : BaseContentObject { /* ... */ } 

[DataContract] 
public class Image : BaseContentObject { /* ... */ } 

然後你可以使用new DataContractSerializer(typeof(BaseContentObject))的一切。

+0

這看起來很有趣。然而,在我的抽象類中,我目前沒有[DataContract]屬性(目前只有繼承類正在裝飾)。我是否也應該修飾抽象? – mare 2010-01-13 12:48:47

0

我寧願使用泛型。 的助手可以是這樣的:

public static string Serialize<T>(T t, IEnumerable<System.Type> types, bool preserveReferences) 
    { 
     StringBuilder aStringBuilder = new StringBuilder(); 
     using (StringWriter aStreamWriter = new StringWriter(aStringBuilder)) 
     { 
      DataContractSerializer aDCS; 
      using (XmlTextWriter aXmlTextWriter = new XmlTextWriter(aStreamWriter)) 
      { 
       aDCS = new DataContractSerializer(typeof(T), types, int.MaxValue, false, preserveReferences, null); 

       aDCS.WriteObject(aXmlTextWriter, t); 
      } 
     } 
     return aStringBuilder.ToString(); 
    } 

泛型將允許您序列化任何你想要的類型,而不使用if語句。