CA2202, how to solve this case

后端 未结 12 1106
闹比i
闹比i 2020-11-22 08:18

Can anybody tell me how to remove all CA2202 warnings from the following code?

public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
    us         


        
12条回答
  •  自闭症患者
    2020-11-22 08:33

    I just wanted to unwrap the code so we can see multiple calls to Dispose on the objects. The reality is that you are calling Dispose on objects twice:

    memoryStream = new MemoryStream()
    cryptograph = new DESCryptoServiceProvider()
    cryptoStream = new CryptoStream()
    streamWriter = new StreamWriter()
    
    memoryStream.Dispose(); //implicitly owned by cryptoStream
    cryptoStream.Dispose(); //implicitly owned by streamWriter
    streamWriter.Dispose(); //through a using
    
    cryptoStream.Dispose(); //INVALID: second dispose through using
    cryptograph.Dispose(); //through a using
    memorySTream.Dipose(); //INVALID: second dispose through a using
    
    return memoryStream.ToArray(); //INVALID: accessing disposed memoryStream
    

    While most .NET class are (hopefully) resilient against the mistake of multiple calls to .Dispose, not all classes are as defensive against programmer misuse.

    Yes, the canonical documentation says that all class must be immune to programmer misuse from multiple calls to .Dispose:

    The object must not throw an exception if its Dispose method is called multiple times

    But this is the real world - where we're trying to eliminate bugs; not cause them. FX Cop knows this, and warns you.

    You have a few choices;

    • only call Dispose once on any object; don't use using
    • keep calling dispose twice, and hope the code doesn't crash
    • suppress the warning

提交回复
热议问题