Reputation: 1921
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); }
}
}
Upvotes: 35
Views: 40412
Reputation: 706
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();
}
}
Upvotes: 3
Reputation: 9011
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
Upvotes: 62
Reputation: 99957
Implement the ISerializable
interface and then use [XmlIgnore]
for XML serialzation in the GetObjectData() method but then output as binary. It's actually simpler than how I just described it.
For ideas, see http://www.c-sharpcorner.com/UploadFile/yougerthen/102162008172741PM/1.aspx
Upvotes: 0
Reputation: 23324
[NonSerialized]
private IList<Number> nums;
public IList<Number> Nums { get {return nums;} set { nums = value; } }
Upvotes: 38
Reputation: 7200
Cheat and use a method
[Serializable()]
public class Foo
{
public IList<Number> Nums { get; set; }
public long GetValueTotal()
{
return Nums.Sum(x => x.value);
}
}
Upvotes: -14