使用'使用'或直接调用'DIspose'进行调用时出现奇怪的'Dispose'错误

时间:2015-01-16 19:46:50

标签: vb.net

我的代码有效:

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 
...

完全不知所措,没有任何解释为什么会出现错误&#34; Dispose不是ChannelFactory的成员&#34;在第二种方法中,但不是在第一种方法中?

1 个答案:

答案 0 :(得分:3)

那是因为ChannelFactory implements IDisposable.Dispose explicitly。您必须将其强制转换为IDisposable才能致电Dispose

Using声明很聪明,可以为你做演员。