用'Using'调用或直接调用'DIspose'时出现奇怪的'Dispose'错误
Strange 'Dispose' Error when calling with 'Using' or directly calling 'DIspose'
我有这个有效的代码:
Option Strict On
Imports System
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Description
...
Private Property Channel As IWSOServiceContract
Public Sub SomeMethod(ByVal url As String)
Using ChlFactory As ChannelFactory(Of IWSOServiceContract) = New ChannelFactory(Of IWSOServiceContract)(New WebHttpBinding(), url)
ChlFactory.Endpoint.Behaviors.Add(New WebHttpBehavior())
Channel = ChlFactory.CreateChannel()
End Using
End Sub
...
但是当我将其重构为:
Option Strict On
Imports System
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Description
...
Private Property ChlFactory As ChannelFactory(Of IWSOServiceContract)
Private Property Channel As IWSOServiceContract
Public Sub SomeMethod(ByVal url As String)
ChlFactory = New ChannelFactory(Of IWSOServiceContract)(New WebHttpBinding(), url)
ChlFactory.Endpoint.Behaviors.Add(New WebHttpBehavior())
Channel = ChlFactory.CreateChannel()
ChlFactory.Dispose() '<-- ERROR HERE BUT HOW DID USING WORK BEFORE?
End Sub
...
完全不知所措,没有任何解释为什么第二种方法有错误"Dispose is not a member of ChannelFactory"而第一种方法没有错误?
那是因为 ChannelFactory
implements IDisposable.Dispose
explicitly。您必须将其转换为 IDisposable
才能调用 Dispose
.
Using
语句足够聪明,可以为您进行转换。
我有这个有效的代码:
Option Strict On
Imports System
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Description
...
Private Property Channel As IWSOServiceContract
Public Sub SomeMethod(ByVal url As String)
Using ChlFactory As ChannelFactory(Of IWSOServiceContract) = New ChannelFactory(Of IWSOServiceContract)(New WebHttpBinding(), url)
ChlFactory.Endpoint.Behaviors.Add(New WebHttpBehavior())
Channel = ChlFactory.CreateChannel()
End Using
End Sub
...
但是当我将其重构为:
Option Strict On
Imports System
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Description
...
Private Property ChlFactory As ChannelFactory(Of IWSOServiceContract)
Private Property Channel As IWSOServiceContract
Public Sub SomeMethod(ByVal url As String)
ChlFactory = New ChannelFactory(Of IWSOServiceContract)(New WebHttpBinding(), url)
ChlFactory.Endpoint.Behaviors.Add(New WebHttpBehavior())
Channel = ChlFactory.CreateChannel()
ChlFactory.Dispose() '<-- ERROR HERE BUT HOW DID USING WORK BEFORE?
End Sub
...
完全不知所措,没有任何解释为什么第二种方法有错误"Dispose is not a member of ChannelFactory"而第一种方法没有错误?
那是因为 ChannelFactory
implements IDisposable.Dispose
explicitly。您必须将其转换为 IDisposable
才能调用 Dispose
.
Using
语句足够聪明,可以为您进行转换。