我有一个界面
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 > ();
编译。
答案 0 :(得分:6)
您已指定:
CryptoWork<T> where T : ICrypto<T>, new()
你正在使用
new CryptoWork<TripleDESCryptoProvider>();
要实现这一目标,我们需要:
TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>
(自T
= TripleDESCryptoProvider
)
但你有:
TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>
和一个公共无参数构造函数(你有)。选项:
TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>
CryptoWork
类型具有2个泛型类型参数;一个用于TripleDESCryptoProvider
,另一个用于TripleDESCryptoServiceProvider