CA2202:不要释放对象多次 [英] CA2202: Do not dispose objects multiple times
问题描述
我有像这样一类...
I have a class like so...
public class Class1
{
public Class1()
{
byte[] plainText = new byte[1024];
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(plainText, 0, plainText.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.Flush();
encrypted = msEncrypt.ToArray();
}
}
}
public ICryptoTransform encryptor { get; set; }
public byte[] encrypted { get; set; }
}
代码分析引发以下警告。不处置对象多次。
Code analysis throws the following warning. Do not dispose objects multiple times.
的 http://msdn.microsoft.com/en-us/library/ms182334.aspx 。
我不能够理解这条线上述[示例节]的文章......嵌套using语句(在Visual Basic中使用)可能会导致侵犯CA2202警告,如果嵌套内部using语句的IDisposable的资源包含外using语句,该处分的资源嵌套资源的方法释放所包含的资源。当这种情况发生时,外using语句的Dispose方法试图出售其资源的第二次。
I am not able to comprehend this line in the article above [Example section]... "Nested using statements (Using in Visual Basic) can cause violations of the CA2202 warning. If the IDisposable resource of the nested inner using statement contains the resource of the outer using statement, the Dispose method of the nested resource releases the contained resource. When this situation occurs, the Dispose method of the outer using statement attempts to dispose its resource for a second time."
< IMG SRC =http://i.stack.imgur.com/13tvh.jpgALT =IL此代码>
推荐答案
据指出,当你调用的Dispose
上的资源,它会处理所有其持有的资源。因此,这里的内部资源 csEncrypt
把握外部资源 msEncrypt
在 csEncrypt.Dispose
将已处理 msEncrypt
以及
It states that when you call Dispose
on a resource, it will dispose all the resource which it holds. So the inner resource here csEncrypt
which holds the outer resource msEncrypt
on csEncrypt.Dispose
it will have disposed msEncrypt
as well.
后来 msEncrypt。 Disopse
被调用,因此代码分析警告您调用的Dispose
多次。
Later msEncrypt.Disopse
is called, so Code Analysis warns you about calling Dispose
multiple times.
这篇关于CA2202:不要释放对象多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!