Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将对象作为值C传递#_C#_Webbrowser Control_Parameter Passing_Argument Passing - Fatal编程技术网

C# 将对象作为值C传递#

C# 将对象作为值C传递#,c#,webbrowser-control,parameter-passing,argument-passing,C#,Webbrowser Control,Parameter Passing,Argument Passing,在将WebBrowser对象导航到C#中的URL时,我将对象:System.Windows.Forms.HtmlElement传递给一个方法,但是如果我将WebBrowser对象导航到另一个页面,HtmlElement对象将变为null。伪代码是: //Code to navigate to a page WebBrowser.Navigate("http://www.google.com"); //pass one of the page's element as parameter in

在将WebBrowser对象导航到C#中的URL时,我将对象:
System.Windows.Forms.HtmlElement
传递给一个方法,但是如果我将WebBrowser对象导航到另一个页面,HtmlElement对象将变为null。伪代码是:

//Code to navigate to a page
WebBrowser.Navigate("http://www.google.com");

//pass one of the page's element as parameter in a method
Method(HtmlElement WebBrowser.Document.Body.GetElementsByTagName("input")["search"]);

Method(HtmlElement Element)
{
  //Works fine till now
  MessageBox.Show(Element.InnerText);

  //Code to navigate to another page
  WebBrowser.Navigate("http://www.different_page.com");

  //Here the Element object throws exception because it becomes null after another navigation to another website.
  MessageBox.Show(Element.InnerText); 
}

元素
持有一个引用,因此它在第二次导航时会丢失其状态。在执行第二次导航之前,请尝试存储值类型(例如
.InnerText
)。

我找到了解决此问题的方法。解决方案是创建一个临时WebBrowser对象,并将其中的元素作为OuterHtml直接传递到主体中,然后导航到该DOM文本,就像它是页面的响应HTML一样:

Method(HtmlElement Element)
{
  MessageBox.Show(Element.InnerText);

  WebBrowser WebBrowser = new WebBrowser();

  WebBrowser.DocumentText = "<html><head></head><body>" + Element.OuterHtml + "</body></html>";

  while (WebBrowserReadyState.Complete != WebBrowser.ReadyState)
            Application.DoEvents();

  MessageBox.Show(WebBrowser.Document.Body.InnerText);
}
方法(HtmleElement元素)
{
MessageBox.Show(Element.InnerText);
WebBrowser WebBrowser=新的WebBrowser();
WebBrowser.DocumentText=“+Element.OuterHtml+”;
while(WebBrowser.ReadyState.Complete!=WebBrowser.ReadyState)
Application.DoEvents();
Show(WebBrowser.Document.Body.InnerText);
}

现在,我可以访问元素:
WebBrowser.Document.Body
,即使我将原始WebBrowser对象导航到另一个页面,该元素仍然存在。

我猜HtmleElement正在丢失引用,因为WebBrowser.Document更改一次。navigate被调用。尝试在.navigateEyes之前将Element.InnerText存储在字符串变量中,这可能是原因…是的,但我还需要其他属性,如GetAttribute。我已经发布了我问题的答案。+1,因为它不需要太多的编码工作就可以完成这项工作。