CA2000:处置对象警告



我有以下方法:

    public byte[] HtmlToDoc(string hmtl, string userId)
    {
        byte[] data;
        var auditor = new ServiceAuditor
        {
            User = userId
        };
        try
        {
            using (var tx = new ServerText())
            {
                tx.Create();
                tx.Load(Server.HtmlDecode(hmtl), StringStreamType.HTMLFormat);
                tx.Save(out data, BinaryStreamType.MSWord);
            }
        }
        catch (Exception e)
        {
            auditor.Errormessage = e.Message + "/n " + e.StackTrace;
            data = new byte[0];
        }
        finally
        {
            auditor.Save();
            auditor.Dispose();
        }
        return data;
    }

我在编译期间收到以下警告:

警告CA2000:Microsoft.reliability:in Method 'doccreator.htmltodoc(字符串,字符串(',对象'new ServiceAuditor((' 并非在所有例外路径上处置。称呼 system.idisposable.dispose在对象" new ServiceAuditor(("之前 对其的引用不超出范围。

很奇怪的是,即使我处置对象,我也不知道为什么它会抱怨。您能指出问题在哪里吗?

您遇到的问题是:

auditor.Save();

如果抛出异常,则下一行无法运行,这是负责处理您的auditor对象的原因。因此,您可以将Save调用在另一个try/catch中,但实际上,您应该只依靠using语句为您执行此操作,因为它隐含地调用Dispose方法,例如:

public byte[] HtmlToDoc(string hmtl, string userId)
{
    byte[] data;
    //Add using statement here and wrap it around the rest of the code
    using(var auditor = new ServiceAuditor { User = userId })
    {
        try
        {
            using (var tx = new ServerText())
            {
                tx.Create();
                tx.Load(Server.HtmlDecode(hmtl), StringStreamType.HTMLFormat);
                tx.Save(out data, BinaryStreamType.MSWord);
            }
        }
        catch (Exception e)
        {
            auditor.Errormessage = e.Message + "/n " + e.StackTrace;
            data = new byte[0];
        }
        finally
        {
            auditor.Save();
            //No need to manually dispose here any more
        }
    }
    return data;
}

感谢@davidg的响应,肯定有一个错误点,但是引起警告的是对象的初始化:

//Add using statement here and wrap it around the rest of the code
using(var auditor = new ServiceAuditor { User = userId })
{
    try
    { ...

应该是:

using(var auditor = new ServiceAuditor())
{
   auditor.User = userId;
    try
    { ...

我在此处找到了此问题的参考Ca2000:处置...

初始化一次性对象的成员不应在 使用语句的构造函数。

相关内容

最新更新