mjr*_*mjr 2 vb.net factory using-statement
假定基类Foo实现IDisposable。类FooA并FooB继承Foo类。一个简单的工厂方法,FooFactory.Create()根据客户端的需要返回FooA或FooB对象。
在下面的客户端代码(FooTest模块)中,尝试在“使用”语句中使用工厂方法会导致以下编译错误:
“使用”资源变量必须具有显式初始化。
我非常感谢有关通过Using语句支持实例化FooA或FooB(由客户端指定)的实现的任何建议(最佳实践)。不需要工厂-这只是我尝试的方法。理想情况下,我希望FooA和FooB是具有公共基类或接口的独立类。
在此先感谢您提供的任何帮助。
Public Module FooTest
Public Sub Test()
'the following compiles:
Dim f As Foo = FooFactory.Create("A")
f.DoWork()
f.Dispose()
'the following causes a compile error:
''Using' resource variable must have an explicit initialization.
Using f As FooFactory.Create("A")
f.DoWork()
End Using
End Sub
End Module
Public Module FooFactory
Public Function Create(ByVal AorB As String) As Foo
If AorB = "A" Then
Return New FooA
Else
Return New FooB
End If
End Function
Public Class FooA : Inherits Foo
End Class
Public Class FooB : Inherits Foo
End Class
Public MustInherit Class Foo : Implements IDisposable
Public Overridable Sub DoWork()
End Sub
Public Overridable Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module
Run Code Online (Sandbox Code Playgroud)
您在“使用”行上的语法错误。像Dim一样编写,用Using代替Dim:
Using f As Foo = FooFactory.Create("A")
Run Code Online (Sandbox Code Playgroud)
您不能说“ As FooFactory.Create”,因为类型必须跟随“ As”关键字。
| 归档时间: |
|
| 查看次数: |
216 次 |
| 最近记录: |