gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:14:59 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

如果您想避免在没有参数的情况下创建它,您可以轻松地将构造函数设为私有(private)。

例如:

public class PgpPublicKey
{
public PgpPublicKey(PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time);

private PgpPublicKey();
// cut other methods
}

关于C#序列化一个没有无参数构造函数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com