using object initializer generates CA 2000 warning

不羁的心 提交于 2019-12-11 06:59:08

问题


Following code generates a CA2000 warning:

Myclass myclass = null;
try
{
   myclass = new Myclass { Name = "a name" };
}
finally
{
   if (myclass != null)
   {
      myclass.Dispose();
   }
}

i found some topics with the same problem and as I understand the problem is, that the compiler generates for the constructor a temporary variable and for this variable I'm not calling Dispose().

var tmp = new MyClass();
tmp.Name = "a name";
myclass = tmp:

so my question is, if there is a solution with using object initializer which not generates a ca2000 warning.

thanks in advanced.


回答1:


As Damien points out in the comments, the FxCop warning is valid, since the C# compiler creates the IDisposable instance in a hidden temp variable, and when an exception is thrown during the initialization of one of the properties that instance will not get disposed.

With a good API design this would not be a problem, since resources (things that implement IDisposable) should contain an Open (or Begin, Start, whatever) method (according to the Framework Design Guidelines), and should not leak before Open is called. This rule is created for the same reason as what you are experiencing: to prevent leaking during initialization. The FDG were written before C# 3.0, but the same problem exists when the an exception is thrown from within the constructor of that instance (which can always happen because of asynchronous exceptions such as thread aborts). Since the reference to the instance isn't published at that point, there is no way for anyone to dispose that instance. Initializing the underlying resources during construction is therefore not advised.

So you can safely discard that warning when Myclass contains some sort of Open method, and when you're not initializing it with values that implement IDisposable themselves. In other cases, you should revert to the following:

var myclass = new MyClass();

try
{
    myclass.Name = "a name";
}
finally
{
    myclass.Dispose();
}


来源:https://stackoverflow.com/questions/8739065/using-object-initializer-generates-ca-2000-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!