无法实例化泛型类

本文关键字:泛型类 实例化 | 更新日期: 2023-09-27 17:54:15

我有一个接口

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>

(since T = TripleDESCryptoProvider)

但是你有:

TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>

和一个公共无参数构造函数(你已经有了)。选择:

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