这是一个一类,一种形式的袖珍应用程序,可导航到特定网站,登录并下载为我们存储的文件。仅有Chrome支持,一切都很好,但是我们办公室的用户可以使用Chrome或Firefox,因此我不得不采用这种方式。
Public Class Form1
Private browser As Object
Private Sub doLogin()
Me.ToolStripStatusLabel1.Text = "Logging in"
If My.Settings.UserBrowser Is BrowserChrome Then
Dim Options = New ChromeOptions
'Set options
Dim driverService = ChromeDriverService.CreateDefaultService()
driverService.HideCommandPromptWindow = True
browser = New ChromeDriver(driverService, Options)
Else
Dim Options = New FirefoxOptions
'Set options
Dim driverService = FirefoxDriverService.CreateDefaultService()
driverService.HideCommandPromptWindow = True
browser = New FirefoxDriver(driverService, Options)
End If
browser.Url = "https://www.example.com"
browser.Navigate()
现在,browser
当然是晚绑定的,但是除了一直为每个浏览器复制代码外,我不知道如何避免在这里晚绑定。
答案 0 :(得分:2)
假设这是硒,那么FirefoxDriver和ChromeDriver都以RemoteWebDriver为基础,但也以WebDriver为接口。
这真的很重要。
通过一个接口,您可以访问共享的方法和属性,而无需知道已实现的类的显式版本。接口被认为是早期绑定,因为可以进行方法调用,而不必搜索可能的候选方法列表,也不必使用System.Reflection来确定类实际上可以做什么。
Private browser As WebDriver
Private Sub doLogin()
Me.ToolStripStatusLabel1.Text = "Logging in"
If My.Settings.UserBrowser Is BrowserChrome Then
Dim Options = New ChromeOptions
'Set options
Dim driverService = ChromeDriverService.CreateDefaultService()
driverService.HideCommandPromptWindow = True
browser = New ChromeDriver(driverService, Options)
Else
Dim Options = New FirefoxOptions
'Set options
Dim driverService = FirefoxDriverService.CreateDefaultService()
driverService.HideCommandPromptWindow = True
browser = New FirefoxDriver(driverService, Options)
End If
browser.Url = "https://www.example.com"
browser.Navigate()
' Do other things...
End Sub
答案 1 :(得分:1)
当对象是动态对象或未知对象时(取决于您的情况),它将仅在运行时绑定,这就是您所看到的。基本上,编译器不知道哪种对象或包含方法和属性的对象的类型,因此它绕过了编译时检查。您可以将其强制转换为适当的类型...
Private browser As Object = Nothing
Private Sub doLogin()
Me.ToolStripStatusLabel1.Text = "Logging in"
If My.Settings.UserBrowser Is BrowserChrome Then
Dim Options = New ChromeOptions
'Set options
Dim driverService = ChromeDriverService.CreateDefaultService()
driverService.HideCommandPromptWindow = True
browser = New ChromeDriver(driverService, Options)
Else
Dim Options = New FirefoxOptions
'Set options
Dim driverService = FirefoxDriverService.CreateDefaultService()
driverService.HideCommandPromptWindow = True
browser = New FirefoxDriver(driverService, Options)
End If
If TypeOf browser Is ChromeDriver Then
CType(browser, ChromeDriver).Url = "https://www.example.com"
CType(browser, ChromeDriver).Navigate()
ElseIf TypeOf browser Is FirefoxDriver Then
CType(browser, FirefoxDriver).Url = "https://www.example.com"
CType(browser, FirefoxDriver).Navigate()
End If
End Sub
或其他可能性...
CType(browser, If(TypeOf browser Is ChromeDriver, ChromeDriver, FirefoxDriver)).Url = "https://www.example.com"
CType(browser, If(TypeOf browser Is ChromeDriver, ChromeDriver, FirefoxDriver)).Navigate()