为什么第二次嵌套'使用' (使用我的Foo,Bar类)不生成CA2202"不要多次丢弃对象"警告。 相同的嵌套"使用"对于IO类型,确实会产生CA2202问题。
谢谢大家 - 任何帮助都将不胜感激。
using System;
using System.IO;
namespace ConsoleApplication1
{
public class Foo : IDisposable
{
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isUserCall)
{
if (isUserCall)
{
}
else
{
}
}
}
public class Bar : IDisposable
{
private Foo _foo;
public Bar(Foo foo)
{
_foo = foo;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isUserCall)
{
if (isUserCall)
{
// call Foo::Dispose as StreamWriter dispose the FileStream
_foo.Dispose();
}
}
}
class Program
{
static void Main(string[] args)
{
// generate FxCop CA2202 with .NET types
using (Stream stream = new FileStream("file.txt", FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(stream))
{
// Use the writer object...
}
}
// not generate the issue with my types... why ?
using (Foo f = new Foo())
{
using (Bar b = new Bar(f))
{
}
}
}
}
}