c# - 使用动态类型

标签 c# wpf c#-4.0

我使用的是 System.Window.Controls Webbrowser (WPF),它会到处抛出一些异常。

通常,如果我想访问 Winforms 中的 webbrowser 文档并单击我会使用的元素

       HtmlDocument document = webNav.webBrowser1.Document;
       document.GetElementById("id_of_element").InvokeMember("Click");

但是,在 WPF 中它会抛出错误 Cannot implicitly convert type 'object' to 'System.Windows.Forms.HtmlDocument'。存在显式转换(是否缺少强制转换?)

我可以通过使用来解决这个问题

       dynamic document = webNav.webBrowser1.Document;
       document.GetElementById("id_of_element").InvokeMember("Click");

是否有更好/首选的方法,或者这是对动态类型的可接受使用? (是否有任何可以接受的使用动态类型的例子?)

最佳答案

如错误所述,您缺少显式转换:

 HtmlDocument document = (HtmlDocument)webNav.webBrowser1.Document;

假设您在文件顶部有 using System.Windows.Forms;(以缩短上面的代码)。

因为这条线,我知道这一点,

An explicit conversion exists (are you missing a cast?)

在这种情况下不需要使用dynamic

关于c# - 使用动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884637/

相关文章:

c# - 如何通过 Windows 窗体 C# 应用程序连接到 Linux 托管数据库?

c# - 单元测试超时

c# - WPF:更改 ContentControl 的内容时,新的内容对象不会触发加载的事件

asp.net - 动态数据 - 从 DropDownList 中选择一个表以在 GridView 中搭建支架

.net - 未找到命名空间网络

c# - System.Threading.ThreadAbortException 在新线程中引发

c# - WPF TextBox 移动光标和改变焦点

c# - 从 MethodInfo 获取 Func<> 的 Delegate.CreateDelegate 不适用于 double 类型?

c# - 将 ElementHost 的大小调整为托管的 XAML UserControl 的大小

c# - 在运行时向 ComboBox 添加项目?