必须隐式转换为System.IDisposable

时间:2015-10-08 09:23:20

标签: c#

我使用(MySqlBackup)时遇到错误。我已经将MySqlBackup.dll添加到其引用中,但我仍然遇到了同样的错误。有谁知道如何解决这个问题?

以下是代码:

public bool createBackup()
    {
        bool ret = false;
        using (var sfd = new SaveFileDialog())
        {
            sfd.Filter = "SQL Backup File (*.sql)|*.sql";
            sfd.FilterIndex = 1;
            sfd.FileName = "MyBackup.sql";

            if (sfd.ShowDialog() == DialogResult.OK && sfd.FileName.Length > 0)
            {
                string file = sfd.FileName;

                using (MySqlConnection con = new MySqlConnection(connect()))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        using (MySqlBackup mb = new MySqlBackup(cmd))
                        {
                            try
                            {
                                cmd.Connection = con;
                                con.Open();
                                mb.ExportToFile(file);
                                con.Close();
                                ret = true;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                    }
                }
            }
        }
        return ret;
    }

3 个答案:

答案 0 :(得分:0)

using在范围结束后立即处理实例。为此,该类必须实现System.IDisposable接口。

如果没有,则无法在using中使用它,也不能在Dispose()中手动使用它。您必须创建其实例并让GarbageCollector为您执行此操作。

所以,你有两个选择:

  • 只需在您的课程上实施System.IDisposable
  • 不使用using

使用:

//inherit from "IDisposable"
class SystemResource : IDisposable
{
    //add Dispose method
    public void Dispose()
    {
    }
}

不使用:

MySqlBackup mb = new MySqlBackup(cmd);
try
{
    cmd.Connection = con;
    con.Open();
    mb.ExportToFile(file);
    con.Close();
    ret = true;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

答案 1 :(得分:0)

由于您使用的是“using(//your class){}”,因此必须实施IDisposable,然后才能支持using(){} block。 检查this链接是否正确使用此声明。

答案 2 :(得分:0)

您不能将MySqlBackup()与块编码一起使用,您只能使用此格式的连接和命令(块),但为此您必须创建其实例并手动处理它。

相关问题