C# serialize a class without a parameterless constructor

后端 未结 5 1909
予麋鹿
予麋鹿 2020-12-18 21:08

I\'m implementing a factory pattern for 3 different cryptography classes. The factory will determine which one to create and then get a serialized instance of the correct cl

5条回答
  •  -上瘾入骨i
    2020-12-18 21:59

    Any Serializer Class need a parameterless constructor because, while deserializing it create an empty new instance, then it copies every public property taken from seialized data.

    You can easily make the constructor private, if you want to avoid to create it without parameters.

    EX:

    public class PgpPublicKey
    {
        public PgpPublicKey(PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time);
    
        private PgpPublicKey();
        // cut other methods
    }
    

提交回复
热议问题