我有以下接口(interface)定义
public interface IEncryptor
{
T Decrypt<T>(byte[] encryptedData) where T : class;
}
有了这个实现(应该不相关)
internal class ThingyEncryptor : IEncryptor
{
public T Decrypt<T>(byte[] encryptedData) where T : class
{
var encryptedSymmetricKey = encryptedData.Take(SymmetricKeyLength).ToArray();
var iv = encryptedData.Skip(SymmetricKeyLength).Take(IvLength).ToArray();
var symmetricEncryptedData = encryptedData.Skip(SymmetricKeyLength + IvLength).ToArray();
using (var rsa = _certificate.GetRSAPrivateKey())
{
var symmetricKey = rsa.Decrypt(encryptedSymmetricKey, RSAEncryptionPadding.Pkcs1);
var clearData = Decrypt(symmetricEncryptedData, symmetricKey, iv);
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(clearData));
}
}
}
阅读 Constraints on type parameters (C# Programming Guide) , 表示:
If client code uses a type that doesn't satisfy a constraint, the compiler issues an error
当像这样调用 Decrypt
方法时,我看不到任何编译器警告或错误(其中 IMyModel
实际上是一个接口(interface)而不是一个类):
_encryptor.Decrypt<IMyModel>(x.Patient)
为什么?
此代码是 nestandard20 项目的一部分。
最佳答案
您误解了类
constraint ,它将提供的类型参数强制为引用类型:
The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type.
关于c# - 为什么不强制对泛型类型进行类约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70848740/