开发者

Change the order of property serialization at design time in .Net

开发者 https://www.devze.com 2022-12-08 21:03 出处:网络
I have a class where it\'s problemati开发者_StackOverflowc to relay on the properties being serialized in alphabetical order at design time.

I have a class where it's problemati开发者_StackOverflowc to relay on the properties being serialized in alphabetical order at design time. In other words, property Z must be serialized before property A.

The problem arises because property property Z clears property A whenever it changes - which happens in InitializeComponent. I work around this problem by setting a FirstTime flag, but that seems messy.

I found a solution here (translated from Spanish), but that seems like over kill.

What's the correct way to handle the problem?


The best practice here is to re-write your class so that all design-time properties are independent of each other. That is how all Microsoft-supplied designable types work.

I have almost fallen into this trap many times before, and I always solved it by making the funny inter-dependencies happen only at run time, not design time.


I am the author of the "overkill" solution. :-) If you don't like the solution based on CodeDomSerializer, I thnik that your only option is to design your class so that properties can be initialized in any order (which is considered good practice anyway). Can you for example have property Z to not clear property A if it is the first time that its setter is invoked? Something like:

bool propertyZHasBeenSet=false;
SomeType propertyZ
{
    get {
        //Property getter
    }

    set {
        if(propertyZHasBeenSet) {
            //Clear property A
        } else {
            propertyZHasBeenSet=true;
        }
        //The remaining of the property setter
    }
}

I'm sure there must be a better way to accomplish the same thing, but you get the idea.

0

精彩评论

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

关注公众号