如何在序列化C#-object时排除属性

时间:2017-09-26 13:39:13

标签: c# serialization

如何阻止属性序列化?我有一个抽象类,类标有[Serializable]。但我不希望Checksum属性包含在序列化中。我该怎么做?

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)的代码,但是当我尝试将其应用于我的代码时,编译器说它在此声明类型上无效,并且它仅在&上有效#39;字段&#39;声明。

// 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 个答案:

答案 0 :(得分:0)

如果要将该类转换为JSON对象,则可以使用[XmlIgnore()][JsonIgnore]装饰您的属性,具体取决于您使用的序列化程序

答案 1 :(得分:0)

自BinaryFormatter序列化字段后,它无法正常工作,请参阅How to Ignore a property from being serialized using BinaryFormatter?

所以我认为解决方案是重新设计我的代码。