获取 RunWorkerCompleteEventArgs 对象的内容

本文关键字:对象 RunWorkerCompleteEventArgs 获取 | 更新日期: 2023-09-27 18:34:46

我正在返回一个RunWorkerCompletedEventArgs对象,我正在尝试获取我可以在该对象中看到的错误号。当我使用if (err.Number!= 2627){}时,出现以下错误

">

对象"不包含"数字"的定义,也没有扩展名 方法"数字"接受类型为"对象"的第一个参数可以是 找到(是否缺少 using 指令或程序集引用?

请有人建议我如何获取对象内容(请参阅下面的即时窗口(。

另外,有人可以解释一下这里实际发生了什么,因为错误表明该对象不包含"数字"的定义,但看起来它确实存在?

法典:

private void GBHworker_RunWorkerCompleted(object sender, 
             RunWorkerCompletedEventArgs e)
{
    //update UI once worker complete his work 
    if (e.Result != null)
    {
        var err = e.Result;
        if (err.Number!= 2627) //don't want to raise error on duplicate primary key
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            var result = ModernDialog.ShowMessage(e.Result.ToString(), 
                         "Error", btn);
        }
    }
}

分配 e:

private void GBHworker_DoWork(object sender, DoWorkEventArgs e)
{
  //....DB parameter setup
  try
  {
    cmd_insert.ExecuteNonQuery();
  }
  catch (Exception crap)
  {
    if (e != null)
      e.Result = crap;
  }
 }

即时窗口:

?err
{"Violation of PRIMARY KEY constraint 'PK_XYZ'. Cannot insert duplicate key in object 'dbo.XYZ. The duplicate key value is (30527293868).'r'nThe statement has been terminated."}
    base {System.Data.Common.DbException}: {"Violation of PRIMARY KEY constraint 'PK_XYZ'. Cannot insert duplicate key in object 'dbo.XYZ'. The duplicate key value is (30527293868).'r'nThe statement has been terminated."}
    Class: 14
    ClientConnectionId: {*******}
    Errors: {System.Data.SqlClient.SqlErrorCollection}
    LineNumber: 1
    Number: 2627
    Procedure: ""
    Server: "*******"
    Source: ".Net SqlClient Data Provider"
    State: 1

获取 RunWorkerCompleteEventArgs 对象的内容

您不需要Result属性来获取异常详细信息,而是使用Error属性,并且由于您期望SqlException,因此将Error转换为SqlException,然后您可以检查Number

if (e.Error != null)
{
   var error = e.Error as SqlException;
   if(eror != null && error.Number == 2627)
     {
      //duplicate key
     }
}

当前您收到错误,因为e.Result类型为 Object ,您必须将其强制转换为特定类型才能访问其属性。

e.Result投射到DbException怎么样?

var exp=e.Result as DbException;
if(exp!=null){
    //NOW USE IT: exp.Number;
}

Result属于Object类型

编辑:- 如果您按照@Habib的建议删除_DoWork中的try/catch,请使用他所说明的以下代码:

var err=e.Error as SqlException;
if(err!=null && err.Number ==2627)
{
    //....
}