2017-09-26 70 views
0

如何防止屬性被序列化?我有一個抽象類,並且該類用[Serializable]標記。但是我不希望Checksum屬性包含在序列化中。我怎麼做?如何在序列化C#時排除屬性 - 對象

using System; 
using System.IO; 
using System.Runtime.Serialization; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.Security.Cryptography; 

namespace test 
{ 

    [DataContract] 
    [Serializable] 
    public abstract class Baseclass 
    { 
     /// <summary> 
     /// The product id. 
     /// </summary> 
     [DataMember(Name = "productId")] 
     public int ProductId { get; set; } 

     /// <summary> 
     /// The calculated checksum for this object. 
     /// It is calculated using SHA1. 
     /// For more information about SHA-1, see https://en.wikipedia.org/wiki/SHA-1 
     /// </summary> 
     [DataMember(Name = "checksum")] 
     public long Checksum 
     { 
      get 
      { 
       long tempHash = 0; 
       try 
       { 
        this.temp = 0; 
        var seraializer = new BinaryFormatter(); 
        var sha1 = new SHA1Managed(); 
        byte[] buffer; 

        using (var memoryStream = new MemoryStream()) 
        { 
         seraializer.Serialize(memoryStream, this); 
         buffer = memoryStream.ToArray(); 
        } 
        var bArrayHash = sha1.ComputeHash(buffer); 
        tempHash = Math.Abs(BitConverter.ToInt64(bArrayHash, 0)); 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex); 
       } 
       return tempHash; 
      } 
     } 
    } 
} 

我試圖從MSDN下面的代碼(https://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx),但是當我嘗試將其應用到我的代碼時,編譯器說,這是不是對這個聲明類型有效的,而且它僅在「有效領域'聲明。

// A test object that needs to be serialized. 
[Serializable()]   
public class TestSimpleObject { 

    public int member1; 
    public string member2; 
    public string member3; 
    public double member4; 

    // A field that is not serialized. 
    [NonSerialized()] public string member5; 

    public TestSimpleObject() { 

     member1 = 11; 
     member2 = "hello"; 
     member3 = "hello"; 
     member4 = 3.14159265; 
     member5 = "hello world!"; 
    } 


    public void Print() { 

     Console.WriteLine("member1 = '{0}'", member1); 
     Console.WriteLine("member2 = '{0}'", member2); 
     Console.WriteLine("member3 = '{0}'", member3); 
     Console.WriteLine("member4 = '{0}'", member4); 
     Console.WriteLine("member5 = '{0}'", member5); 
    } 
} 
+2

在要忽略的成員上使用'[IgnoreDataMember]'屬性。 –

+0

自從BinaryFormatter對字段進行序列化後,它就無法工作了(請參閱https://stackoverflow.com/questions/27286034/how-to-ignore-a-property-from-being-serialized-using-binaryformatter)。 –

回答

0

您可以[XmlIgnore()][JsonIgnore]裝點你的財產,如果你是在該類轉換成JSON對象,這取決於串行您使用

相關問題