谁能告诉我如何从以下代码中删除所有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();
    }
}



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

最佳答案

编译时没有警告:

    public static byte[] Encrypt(string data, byte[] key, byte[] iv)
    {
        MemoryStream memoryStream = null;
        DESCryptoServiceProvider cryptograph = null;
        CryptoStream cryptoStream = null;
        StreamWriter streamWriter = null;
        try
        {
            memoryStream = new MemoryStream();
            cryptograph = new DESCryptoServiceProvider();
            cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write);
            var result = memoryStream;
            memoryStream = null;
            streamWriter = new StreamWriter(cryptoStream);
            cryptoStream = null;
            streamWriter.Write(data);
            return result.ToArray();
        }
        finally
        {
            if (memoryStream != null)
                memoryStream.Dispose();
            if (cryptograph != null)
                cryptograph.Dispose();
            if (cryptoStream != null)
                cryptoStream.Dispose();
            if (streamWriter != null)
                streamWriter.Dispose();
        }
    }

根据评论编辑:
我只是再次验证了此代码不会生成警告,而原始代码会生成警告。
在原始代码中,CryptoStream.Dispose()MemoryStream().Dispose(实际上被调用了两次(可能有问题也可能没有问题)。

修改后的代码如下:将引用设置为null,一旦处置责任转移到另一个对象。例如。成功调用memoryStream构造函数后,将null设置为CryptoStream。成功调用cryptoStream构造函数后,null设置为StreamWriter。如果没有异常,则将streamWriter放置在finally块中,然后依次处置CryptoStreamMemoryStream

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

10-10 18:29