作为我们2010年视觉演播室(主要是C# 4.0)发展标准的一部分,我们改变了《守则分析》。 在我审查最近提交的新项目守则时,我看到了一个避风港。
CA2000 : Microsoft.Reliability: In method XYZ , object ABC is not disposed along all exception paths. Call System.IDisposable.Dispose on object ABC before all references to it are out of scope.
警告。 问题在于,我似乎没有消除这些警告——我花了几个小时时间鼓励网络并尝试我能够做的一切。
首先,让我清楚地看到,我并不是说要简单地使用块来妥善处理地方变量——这不是一个问题。 就我而言,当物体通过方法归还或按照方法分配给另一物体时,这些警告就出现。
此处是包含四项此类警告的法典样本:
public void MainMethod()
{
var object1 = CreateFirstObject(); // Warning here
var object2 = CreateSecondObject(); // Warning here
SomeCollectionProperty.Add(object1);
SomeCollectionProperty.Add(object2);
}
private SomeObject CreateFirstObject()
{
var theObject = new SomeObject() // Warning here
{
FirstProperty = "some value",
// ...
};
return theObject;
}
private SomeOtherObject CreateSecondObject()
{
var theObject = new SomeOtherObject() // Warning here
{
FirstProperty = "a different value",
// ...
};
return theObject;
}
我评论了发出警告的路线。
我曾尝试对MSDN条款(here)所述两种方法进行重新评价,但警告仍然出现。
UPDATE I should note that both SomeObject and SomeOtherObject implement IDisposable.
Also, while object initializers may be a component of the problem, keep in mind that the initializers are isolated to the two private methods and have nothing to do with the warnings in MainMethod.
Can anyone show me how to properly implement these methods to eliminate the CA2000 warnings?