gpt4 book ai didi

c# - 无法实例化泛型类

转载 作者:行者123 更新时间:2023-11-30 14:34:14 25 4
gpt4 key购买 nike

我有一个接口(interface)

public interface ICrypto<T> : IDisposable
{
ICryptoTransform GetDecryptor();

ICryptoTransform GetEncryptor();

T GetAlgorithm();
}

我有一个实现

public class TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>
{

public TripleDESCryptoProvider() { }

public ICryptoTransform GetDecryptor()
{
return GetAlgorithm().CreateDecryptor();
}

public ICryptoTransform GetEncryptor()
{
return GetAlgorithm().CreateEncryptor();
}

public TripleDESCryptoServiceProvider GetAlgorithm()
{
...
}

public void Dispose()
{
throw new NotImplementedException();
}
}

我有一个实现上面实现的类

public class CryptoWork<T> where T : ICrypto<T>, new()
{
protected static T _keyStore;

public static T KeyStore
{
get
{
if (_keyStore == null)
{
_keyStore = new T();
}
return _keyStore;
}
}

/// <summary>
/// Encrypt a byte array
/// </summary>
public string Encrypt(string input)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
using (var encryptor = KeyStore.GetEncryptor())
{
return Convert.ToBase64String(encryptor.TransformFinalBlock(inputArray, 0, inputArray.Length));
}
}

/// <summary>
/// Decrypt a byte array
/// </summary>
public string Decrypt(string input)
{
byte[] inputArray = Convert.FromBase64String(input);
using (var encryptor = KeyStore.GetDecryptor())
{
return UTF8Encoding.UTF8.GetString(encryptor.TransformFinalBlock(inputArray, 0, inputArray.Length));
}
}
}

我在实例化类时遇到问题 CryptoWork<T> where T : ICrypto<T>, new() :

都不是

 var cryptoWork = new CryptoWork < ICrypto < TripleDESCryptoProvider > > ();

也不

var cryptoWork = new CryptoWork < TripleDESCryptoProvider > ();

编译。

最佳答案

您已指定:

CryptoWork<T> where T : ICrypto<T>, new()

你正在使用

new CryptoWork<TripleDESCryptoProvider>();

为此,我们需要:

TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>

(因为 T = TripleDESCryptoProvider )

但是你有:

TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>

和一个公共(public)的无参数构造函数(你有)。选项:

  • 制作TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>
  • 重构 API
  • 制作CryptoWork类型有 2 个泛型类型参数;一个用于 TripleDESCryptoProvider , 另一个为 TripleDESCryptoServiceProvider

关于c# - 无法实例化泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390137/

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