Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore binary serialization on a property

I have a regular C# POCO. At the class level, I am decorating the object with [Serializable()].

That said, I am using the Linq Sum() on one of the properties and I am receiving an error upon serialization. If possible, I would like to just simply ignore this property. However, the [XmlIgnore()] is only for Xml Serialization, not Binary. Any ideas or thoughts?

The code is something like this, where I would like to ignore ValueTotal:

[Serializable()]
public class Foo
{
  public IList<Number> Nums { get; set; }

  public long ValueTotal
  {
    get { return Nums.Sum(x => x.value); }
  }
}
like image 948
Jessy Houle Avatar asked Feb 25 '10 15:02

Jessy Houle


3 Answers

ValueTotal is already ignored. Only data is serialized, not methods. Properties are methods actually.

If you wish to ignore fields and not serialize them mark them as [NonSerialized].

'Or'

you can implement ISerializable and not serialize those field.

Here is some sample code on how can implement ISerializable and serialize data: http://www.c-sharpcorner.com/UploadFile/yougerthen/102162008172741PM/1.aspx

like image 170
ata Avatar answered Oct 18 '22 14:10

ata



    [NonSerialized]
    private IList<Number> nums;
    public IList<Number> Nums { get {return nums;} set { nums = value; }  } 
like image 33
Henrik Avatar answered Oct 18 '22 14:10

Henrik


There is another way that is not listed here that has some benefits(the code below was made to support both binary serialization and xml)(for your example you would need a custom class to serialize your interfaces):

    [OnSerializing]
    private void OnSerializing(StreamingContext context)
    {
        xmlShape4Port = new xmlStreamShape(shape4Port);
        shape4Port = null;
    }
    [OnDeserialized]
    private void OnDeserialized(StreamingContext context)
    {
        if (xmlShape4Port != null)
        {
            shape4Port = xmlShape4Port.getShapeFromSaved();
            xmlShape4Port = null;
        }
    }

    [XmlIgnore()]
    public virtual StreamShape shape4Port {get;set;}

    [XmlElement("shape4Port")]
    public xmlStreamShape xmlShape4Port
    {
        get
        {
            if (shape4Port == null)
                return null;
            else
            {
                return new xmlStreamShape(shape4Port);
            }
        }
        set
        {
            shape4Port = value.getShapeFromSaved();
        }
    }
like image 3
Bostwick Avatar answered Oct 18 '22 16:10

Bostwick