开发者

A read only (immutable) serializeable class

I've designed a class that has with two properties - as string type and a list of objects. I'm loading some xml and deserializing it into an instance of the class, which works very well. What I want is for everything about each instance to be immutable. These classes are exposed as an API, and for 开发者_开发问答integrity, I don't want values of the object to be changed. If a programmer wants something different they should be creating new instances and setting the values then.

Normally I would do this with the ReadOnlyCollection and readonly properties, but that messes up the deserialization. What kinds of things can I do here?


It's not worth polluting your domain model just be be more xml serializer friendly so you can implement ISerializable Interface and write your own serialization routine for any collection that is not serialization friendly.

void GetObjectData(SerializationInfo info, StreamingContext context)
{
  // ...
}


You could implement ISerializable in your class. That way, when the class is deserialized a special constructor is called and you can keep your class truly immutable


Implement the ISerializable interface and do that manually

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜