How can I prevent a auto implemented property from being serialized by the binary formatter? The [NonSerialized] attribute can only be used with fields. And the field is hidden when using auto implemented properties.
It´s not supported for auto implemented properties. You have to use a backing field and set the NonSerializedAttribute on it.
public class ClassWithNonSerializedProperty {
[NonSerialized]
private object _data; // Backing field of Property Data that is not serialized
public object Data{
get { return _data; }
set { _data = value; }
}
}
// This works for the underlying delegate of the `event` add/remove mechanism.
[field:NonSerialized]
public event EventHandler SomethingHappened;
But it doesn't seem to for auto-implemented properties. I thought it was worth mentioning because it's useful to know when serializing an object with event subscribers attached to it.
If you're serializing to Json and using the Json.NET serializer (which I'd highly recommend as it has a lot more to offer than a number of other serializers on the market) then you can achieve your desired outcome on properties using [JsonIgnore]
.
You don't need to create a field.
So your code would be:
public class ClassName
{
[JsonIgnore]
public object IgnoreMe { get; set; }
public object DoNotIgnoreMe { get; set; }
}
If you are serializing to Xml then you can use XmlIgnore attribute.
I'm not sure you can. This MSDN article on SerializableAttribute
suggests you implement ISerializable and control the serialisation yourself:
All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process.
Or switch away from an auto-property for that specific field.
It's not possible for auto implemented properties. Consider folowing:
This behavior is "by design". The decision at the time auto-properties were implemented was that they would work in the "common case" which among other things means no attributes on the generated field. The idea behind that is keeping them simple and not slowly mutating them into full properties. So, if you need to use the NonSerialized attribute full properties are the way.
The proposed solution of using not-serialized backing field does not seem to function properly with .NET 4.0 (at least in the case of Xml serialization). The field indeed does not get serialized but public property that uses it does serialize and thus defeats the purpose. Using XmlIgnore workaround helps in case of Xml serialization. Disclaimer - I did not verify binary serialization behavior.
来源:https://stackoverflow.com/questions/1728367/how-to-prevent-auto-implemented-properties-from-being-serialized