开发者

Pseudo readonly property on with serialization

How bad is some开发者_如何学Cthing like:

public class Test
{
    private string pKey = null;
    public string Key { 
        get { return pKey; } 
        set { if (pKey==null) pKey=value;} 
    }
}

This would allow me to use XMLSerializer with the class and make sure that Key can't be changed after being initially set.


I agree that my initial idea was bad.

I now know that there is no way to make this using the standard XML Serializer. 'ssg' suggestion won't be serialized because it doesn't have a public setter.

The only choices here are implementing the IXmlSerializable, or using another serialization method, like DataContractSerializer. The problem with the former is that every derivate of the class would also have to implement IXmlSerializable; the problem with the latter is that you can't use attributes or have much control over the generated XML.


Bad, consider:

test.pKey = null;
test.Key = 'my new key';

I've managed to circumvent your protection (obviously you could add a null check to the set method to fix this issue).

The same problem could occur if the deserialized object had a null key, the key could still be set the first time it was accessed... It seems like if you need this sort of protection, you should probably look at another way of getting it.

The XMLSerializer places restrictions on the classes you use with it and by trying to work around those restrictions, you’re likely to cause confusion. If you are a one-man shop and you are the only person that looks at the code, this may be less of an issue (at least until you step away from the code for a coupld of months), however in a multi-developer environment the behaviour of your class is likely to cause confusion. For example, you’re hiding the assignment not working by not throwing an exception, so assignment operations would compile and run, but, not update the object and not throw an exception to indicate the failure (which could lead to some hard to track down bugs).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜