简体   繁体   中英

C# Serialization and properties

I have a kind of foreignkey implementation, so that my class has a field that is a reference to another object, and then it has a property that fetches the other object on demand:

[Serializable]
public class MyClass {
    private string otherId;
    public SomeClass Other {
        get { return SomeClass.GetById(otherId); }
        set { otherId = value.id; }
    }
}

Now, can anyone please explain what happens when I serialize/deserialize this class using C# default serialization (I'd like to understand both binary and XML serialization please)

The simple answer is that the serializer, regardless of the target format, is going to call your getter and then serialize the Other property as SomeClass . Whether that is going to throw an exception or not depends on what SomeClass.GetById actually does.

SomeClass is implied as serializable because it is a property of a serializable object.

Both otherId and Other members will be serialized/deserialized.

To stop Other property from being serialized, you can use [IgnoreDataMember] attribute on that property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM