Bri*_*ett 14 c# code-analysis idisposable ca2000
我有一个工厂方法来构建实现的对象IDisposable.最终,调用者可以管理创建对象的生命周期.这种设计引发了一堆CA2000错误.在我的设计中是否存在根本不正确的东西,是否需要重构,还是仅仅对静态代码分析警告过于兴奋?
工厂方法
public static DisposableType BuildTheDisposableType(string param1, int param2)
{
var theDisposable = new DisposableType();
// Do some work to setup theDisposable
return theDisposable
}
Run Code Online (Sandbox Code Playgroud)
来电者
using(var dt = FactoryClass.BuildTheDisposableType("data", 4))
{
// use dt
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*l X 17
您应该将它存储到本地变量,并在try-catch-rethrow块中包装初始化,以防出现任何异常:
public MyDisposable CreateDisposable()
{
var myDisposable = new MyDisposable();
try
{
// Additional initialization here which may throw exceptions.
ThrowException();
}
catch
{
// If an exception occurred, then this is the last chance to
// dispose before the object goes out of scope.
myDisposable.Dispose();
throw;
}
return myDisposable;
}
Run Code Online (Sandbox Code Playgroud)
当Dispose不会被调用时,尽量不要让一次性对象容易受到异常的影响
PS:之前提到的有人在最后处理 - 这显然是错误的 - 在非异常路径中你不想打电话 Dispose
Joh*_*ers 10
我建议您在每个单独的工厂方法上抑制CA2000警告,或者可能在包含它们的整个类上抑制CA2000警告(但仅当它是该类的唯一函数时).
我进一步建议你包括一个理由:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "This is a factory method. Caller must dispose")]
Run Code Online (Sandbox Code Playgroud)