问题描述
我正在为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#序列化没有无参数构造函数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!