C#序列化没有无参数构造函数的类

编程入门 行业动态 更新时间:2024-10-27 12:27:57
本文介绍了C#序列化没有无参数构造函数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为3种不同的密码学类实现工厂模式。工厂将确定要创建哪个实例,然后从数据库中获取正确类的序列化实例,并将其返回给请求者。 现在我正在序列化类以将它们存储在数据库中。我正在为称为 BouncyCastle 的PGP密码学类编写一个。我可以从文件创建类和键,但是当我尝试对其进行序列化时,它说两个成员变量分别是类 PgpPublicKey 和 PgpPrivateKey ,因为它们没有无参数的构造函数而无法序列化。

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 class from a database and return it to the requester. Right now I'm working on serializing the classes to store them in the database. I'm writing one for a PGP cryptography class called BouncyCastle. I can create the class and the keys from files but when I try to serialize it, it says that the two member variables, which are objects of class PgpPublicKey, and PgpPrivateKey, cannot be serialized because they do not have parameterless constructors.

public void createdBouncyFromFiles() { var bc = new BouncyCastle("C:\\TestFiles\\BouncyPublicKey.txt", "C:\\TestFiles\\BouncyPrivateKey.txt", "Password1"); var xmlSerializer = new XmlSerializer(bc.GetType()); var textWriter = new StringWriter(); xmlSerializer.Serialize(textWriter, bc); var theSerializedClass = textWriter.ToString(); }

该类有两个成员变量。

public class BouncyCastle : ICryptographyProvider { public PgpPublicKey m_publicKey; public PgpPrivateKey m_privateKey; public string m_passPhrase; // cut out the irelevant parts

这是公钥类。没有无参数的构造函数。

This is the public key class. No parameterless constructor.

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

推荐答案

任何Serializer类都需要一个无参数的构造函数,因为在反序列化它时会创建一个空的新实例,然后它会复制从序列化数据中获取的每个公共属性。

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 }

更多推荐

C#序列化没有无参数构造函数的类

本文发布于:2023-11-09 06:23:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有无   函数   参数   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!