2013-02-28 49 views
2

C#有沒有辦法從動態序列化中排除成員?C#有沒有辦法從動態序列化中排除成員?

例如(我做了這個代碼,而不是真正的)

類DEF:

[Serializable] 
public class Class1 
{ 
    public int Property1{get;set;} 
} 

和我做

Class1 c=new Class(){Property1=15}; 
SerializationOption option = new SerializationOption(){ExludeList=new List(){"Property1"}}; 
var result=Serialize(Class1,option); 
+0

是添加屬性而不是選項?例如。 '[XmlIgnore] public int Property1 {get;組; }' – DiskJunky 2013-02-28 23:29:59

+0

這不是XmlSerialization,它是.Net序列化。 – codekaizen 2013-02-28 23:30:30

回答

4

來控制這個問題的唯一辦法是落實科學類ISerializable和訪問在序列化期間的某些情況下。例如:

public class Class1 : ISerializable 
{ 
    // .... 
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) 
    { 
     var excludeList = (List<String>)context.Context; 

     if(!excludeList.Contains("Property1")) 
     { 
      info.AddValue("Property1",Property1); 
     } 
    } 
} 

您在創建格式化程序期間提供此上下文。例如:

var sc = new StreamingContext(StreamingContextStates.All, 
           new List<String> { "Property1" }); 
var formatter = new BinaryFormatter(null, sc); 
相關問題