有什麼不對下面code..The給出的代碼是不是投訴CA2000:失去範圍(https://msdn.microsoft.com/library/ms182289.aspx)之前釋放對象。這個代碼生成以下警告.NET代碼分析警告
警告CA2000在方法CryptoComputer.Encrypt(字符串,字符串,字符串,字符串)',對象'new RijndaelManaged()'不沿着所有的異常路徑。調用System.IDisposable.Dispose對象'new RijndaelManaged()'之前,所有對它的引用超出範圍。
public static string Encrypt(string plainText, string passPhrase, string saltValue, string initVector)
{
var initVectorBytes = Encoding.UTF8.GetBytes(initVector);
var saltValueBytes = Encoding.UTF8.GetBytes(saltValue);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
string cipherText;
PasswordDeriveBytes password = null;
RijndaelManaged symmetricKey = null;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize/8);
symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherTextBytes = memoryStream.ToArray();
cipherText = Convert.ToBase64String(cipherTextBytes);
}
catch (Exception)
{
throw;
}
finally
{
password?.Dispose();
symmetricKey?.Dispose();
memoryStream?.Dispose();
}
return cipherText;
}
我怎麼可以重寫這段代碼,以滿足微軟的準則
使用 「使用(......)」 爲密碼,symmetricKey,MemoryStream的。 –
或者是因爲Microsoft的分析規則不能識別「password?.Dispose()」的語法?如果將其重寫爲'if(obj!= null)obj.Dispose();'? – kennyzx
Kennyzx可能是正確的...您必須以舊方式編寫代碼或者抑制虛假警告 –