为什么 class 不强制对泛型类型进行约束?
Why is class constraint on generic type not enforced?
我有以下接口定义
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
实际上是一个接口而不是 class):
_encryptor.Decrypt<IMyModel>(x.Patient)
为什么?
此代码是 nestandard20 项目的一部分。
您误解了 class
constraint,它强制提供的类型参数为引用类型:
The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type.
我有以下接口定义
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
实际上是一个接口而不是 class):
_encryptor.Decrypt<IMyModel>(x.Patient)
为什么?
此代码是 nestandard20 项目的一部分。
您误解了 class
constraint,它强制提供的类型参数为引用类型:
The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type.