gpt4 book ai didi

c# - CA2202,如何解决这个问题

转载 作者:太空狗 更新时间:2023-10-29 22:00:24 26 4
gpt4 key购买 nike

谁能告诉我如何从以下代码中删除所有 CA2202 警告?

public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
using(MemoryStream memoryStream = new MemoryStream())
{
using (DESCryptoServiceProvider cryptograph = new DESCryptoServiceProvider())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
using(StreamWriter streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(data);
}
}
}
return memoryStream.ToArray();
}
}

Warning 7 CA2202 : Microsoft.Usage : Object 'cryptoStream' can be disposed more than once in method 'CryptoServices.Encrypt(string, byte[], byte[])'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 34

Warning 8 CA2202 : Microsoft.Usage : Object 'memoryStream' can be disposed more than once in method 'CryptoServices.Encrypt(string, byte[], byte[])'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 34, 37

您需要 Visual Studio 代码分析才能看到这些警告(这些不是 c# 编译器警告)。

最佳答案

在这种情况下,您应该取消警告。处理一次性用品的代码应该是一致的,您不必关心其他类是否拥有您创建的一次性用品的所有权,也不必对它们调用 Dispose

[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] Encrypt(string data, byte[] key, byte[] iv) {
using (var memoryStream = new MemoryStream()) {
using (var cryptograph = new DESCryptoServiceProvider())
using (var cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write))
using (var streamWriter = new StreamWriter(cryptoStream)) {
streamWriter.Write(data);
}
return memoryStream.ToArray();
}
}

更新:在IDisposable.Dispose您可以阅读以下文档:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times.

可以说这条规则的存在是为了让开发人员可以在一系列一次性用品中合理地使用 using 语句,就像我在上面展示的那样(或者这可能只是一个很好的副作用).因此,出于同样的原因,CA2202 没有任何用处,应该在项目方面予以禁止。真正的罪魁祸首是 Dispose 的错误实现,以及 CA1065应该处理好(如果这是你的责任)。

关于c# - CA2202,如何解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com