Error creating unserialized attribute

I am trying to serialize an object with a nested class. I have been marked with a [NonSerialized] attribute in the nested class, but I get an error:

The "NonSerialized" attribute is not valid for this ad type. It is valid only for field declarations.

How to omit a nested class from serialization?

I have included some code that can show what I'm trying to do. Thanks for any help.

[Serializable] public class A_Class { public String text { get; set; } public int number { get; set; } } [Serializable] public class B_Class { [NonSerialized] public A_Class A { get; set; } public int ID { get; set; } } public byte[] ObjectToByteArray(object _Object) { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, _Object); return stream.ToArray(); } } void Main() { Class_B obj = new Class_B() byte[] data = ObjectToByteArray(obj); } 
+6
c # serialization serializable
source share
3 answers

The error tells you everything you need to know: NonSerialized can only be applied to fields, but you are trying to apply it to a property, albeit an auto-property.

The only real option you have is not to use the auto property for this field, as indicated in this fooobar.com/questions/145337 / ....

+9
source share

Try to explicitly use the support field, which you can mark as [NonSerialized]

 [Serializable] public class B_Class { [NonSerialized] private A_Class a; // backing field for your property, which can have the NonSerialized attribute. public int ID { get; set; } public A_Class A // property, which now doesn't need the NonSerialized attribute. { get { return a;} set { a= value; } } } 

The problem is that the NonSerialized attribute NonSerialized valid for fields, but not for properties, so you cannot use it in conjunction with automatically implemented properties.

+7
source share

Also consider the XmlIgnore attribute for the property:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx

IIRC, properties are automatically ignored for binary serialization.

+7
source share

All Articles