[英]pass object as value C#
在将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);
}
Element
持有一个引用,因此在第二个导航中它失去了状态。 在执行第二个导航之前,请尝试存储值类型(例如.InnerText
)。
我找到了解决该问题的方法。 解决方案是创建一个临时WebBrowser对象,并将其中的Element作为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);
}
现在,我可以通过以下方式访问Element: WebBrowser.Document.Body
并且即使我将原始WebBrowser对象导航到另一个页面,该元素仍然存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.