本文介绍了C#System.InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到这个错误?

  System.InvalidCastException是未处理由用户code
  消息=指定的转换是无效的。
  来源= System.Windows.Forms的
  堆栈跟踪:
       在System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
       在System.Windows.Forms.WebBrowser.get_Document()
       在System.Windows.Forms.WebBrowser.get_DocumentStream()
       在System.Windows.Forms.WebBrowser.get_DocumentText()
       在SiteBot.MainWindow.backgroundWorker1_DoWork(对象发件人,DoWorkEventArgs E)在D:\文档\ Visual Studio 2010的\项目\ SiteBot \ MainWindow.cs:行35
       在System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs E)
       在System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object参数)
  的InnerException:
 

解决方案

以下解决您的跨线程的问题。

 公共委托串GetStringHandler();
公共字符串GetDocumentText()
{
    如果(InvokeRequired)
        返回调用(新GetStringHandler(GetDocumentText))的字符串;
    其他
        返回webBrowser.DocumentText;
}

如果(regAddId.IsMatch(GetDocumentText()))
{
}
 

Why I'm getting this error?

System.InvalidCastException was unhandled by user code
  Message=Specified cast is not valid.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
       at System.Windows.Forms.WebBrowser.get_Document()
       at System.Windows.Forms.WebBrowser.get_DocumentStream()
       at System.Windows.Forms.WebBrowser.get_DocumentText()
       at SiteBot.MainWindow.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\Documents\Visual Studio 2010\Projects\SiteBot\MainWindow.cs:line 35
       at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
       at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
  InnerException: 
解决方案

The following solves your cross thread issue.

public delegate string GetStringHandler();
public string GetDocumentText()
{
    if (InvokeRequired)
        return Invoke(new GetStringHandler(GetDocumentText)) as string;
    else
        return webBrowser.DocumentText;
}

if (regAddId.IsMatch(GetDocumentText()))
{
}

这篇关于C#System.InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 20:39