Consider this class:
[Persistable]
public sealed class FileMoveTask : TaskBase
{
[PersistMember]
public string SourceFilePath { get; private set;}
[PersistMember]
public string DestFilePath { get; private set;}
public FileMoveTask(string srcpath, string dstpath)
{
this.SourceFilePath = srcpath;
this.DestFilePath = dstpath;
//possibly other IMPORTANT initializations
}
//code
}
I can persist the objects of this class, by serializing all the members with attribute PersistMember. But I’m facing some problems (design problems) during the deserialization process. In particular, the problem is with the “possibly other IMPORTANT initializations” which might be there in the constructor, and the programmer may decide not to make few members persistable (i.e not adding PersistMember to them) possibly because that doesn’t make sense.
In such situation, how would I deserialize the object to the exact same state as it was? I suppose, this question boils down to this: how would I call the non-default constructor, passing the same arguments to it, which was passed before? Is there any way to do that? Can we make some rules which can be enforced by the compiler (sort of metaprogramming)? Constructor attributes can help here?
You can solve that in two ways. Use convention over configuration (name the constructor parameters as the properties and do not include a default constructor):
Explicitly tag the constructor arguments with your attribute and search for the constructor which have been tagged:
the attribute or the argument name isn’t used to know which property to set, but to know which information from the serialize data to use when invoking the constructor.