gpt4 book ai didi

vb.net - VB 中的后期绑定(bind)和类型问题

转载 作者:行者123 更新时间:2023-12-04 17:07:07 39 4
gpt4 key购买 nike

我正在尝试通过另一个应用程序运行最初使用 Visual Studio 创建的代码,该应用程序不允许后期绑定(bind),并且很遗憾无法更改此选项。总的来说,我对编程非常陌生,并且努力解决这个问题。这是我在调用代码阶段使用的代码:

Dim objIEShell As Object = CreateObject("Shell.Application")
Dim objIEShellWindows As Object = objIEShell.Windows
Dim objIEWin As Object
For Each objIEWin In objIEShellWindows
If InStr(objIEWin.LocationURL,"google")>0 Then
objIEWin.Quit
objIEWin = Nothing
End If
Next

该代码只是简单地关闭 URL 中带有“google”的所有 Internet Explorer 实例。这是我在尝试编译时收到的错误消息:
Message: Error compiling code
error BC30574: Option Strict On disallows late binding. At line 2
error BC32023: Expression is of type 'Object', which is not a collection type. At line 4

从我到目前为止所做的研究中,我意识到第 2 行的第一条错误消息与 objIEShell 和 Windows 方法之间的类型差异有关。我想我必须转换 objIEShell像这样, CType(objIEShell,?) ,但我不知道 .Windows 方法的类型或如何找出它。此外,任何有关如何修复第二个错误的见解都将不胜感激,因为我也不确定从哪里开始。

最佳答案

这可以追溯到微软仍然计划让 Explorer 像 Web 浏览器一样运行的不稳定时期。很难得出正确的代码,它是两个相互没有太大关系的独立 COM 组件的组合。

您需要首先添加对这些组件的两个引用,以便编译器理解这些名称。使用 Project > Add Reference > COM 选项卡并勾选“Microsoft Internet Controls”和“Microsoft Shell Controls and Automation”。这添加了 Shell32 和 SHDocVw 命名空间。

现在您可以像这样编写早期绑定(bind)的代码:

    Dim objIEShell = New Shell32.Shell
Dim objIEShellWindows = CType(objIEShell.Windows, SHDocVw.IShellWindows)
Dim objIEWin As SHDocVw.WebBrowser
For Each objIEWin In objIEShellWindows
If InStr(objIEWin.LocationURL, "google") > 0 Then
objIEWin.Quit()
End If
Next

CType() 表达式可能是最不直观的表达式,Shell.Windows 属性是 Object 类型,以打破这两个组件之间的依赖关系。类型转换是让编译器满意的必要巫术。

关于vb.net - VB 中的后期绑定(bind)和类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47319701/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com