serialized serialize serializacion deserialize deserializacion and c# serialization

c# - serialize - Ignorar la serialización binaria en una propiedad



serialization and deserialization in c# (5)

Chepa y usa un método

[Serializable()] public class Foo { public IList<Number> Nums { get; set; } public long GetValueTotal() { return Nums.Sum(x => x.value); } }

Tengo un C # POCO regular. En el nivel de clase, estoy decorando el objeto con [Serializable()] .

Dicho esto, estoy usando Linq Sum() en una de las propiedades y recibo un error en la serialización. Si es posible, me gustaría simplemente ignorar esta propiedad. Sin embargo, [XmlIgnore()] es solo para Serialización Xml, no Binario. ¿Alguna idea o pensamiento?

El código es algo así, donde me gustaría ignorar ValueTotal :

[Serializable()] public class Foo { public IList<Number> Nums { get; set; } public long ValueTotal { get { return Nums.Sum(x => x.value); } } }


Hay otra forma que no se enumera aquí que tiene algunos beneficios (el código siguiente se creó para admitir tanto la serialización binaria como xml) (para su ejemplo, necesitaría una clase personalizada para serializar sus 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(); } }



ValueTotal ya está ignorado. Solo los datos se serializan, no los métodos. Las propiedades son métodos en realidad.

Si desea ignorar campos y no serializarlos, [NonSerialized] como [NonSerialized] .

''O''

puedes implementar ISerializable y no serializar esos campos.

Aquí hay algunos ejemplos de código sobre cómo implementar ISerializable y serializar datos: http://www.c-sharpcorner.com/UploadFile/yougerthen/102162008172741PM/1.aspx


[NonSerialized] private IList<Number> nums; public IList<Number> Nums { get {return nums;} set { nums = value; } }