vb.net - 在 Using 语句中通过工厂创建一次性对象

标签 vb.net factory using-statement

假设基类 Foo 实现了 IDisposable。类 FooAFooB 继承类 Foo。一个简单的工厂方法 FooFactory.Create() 根据客户端的需要返回 FooA 或 FooB 对象。

在下面的客户端代码(FooTest 模块)中,尝试在“Using”语句中使用工厂方法会导致以下编译错误:

'Using' 资源变量必须有显式初始化。

对于支持通过 Using 语句实例化 FooA 或 FooB(由客户指定)的实现的任何建议(最佳实践),我将不胜感激。不需要工厂 - 这只是我尝试过的方法。理想情况下,我希望 FooA 和 FooB 是具有公共(public)基类或接口(interface)的独立类。

提前感谢您提供的任何帮助。

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

最佳答案

只是 Using 行的语法错误。像Dim一样写,用Using代替Dim:

Using f As Foo = FooFactory.Create("A")

您不能说“As FooFactory.Create”,因为类型必须跟在“As”关键字之后。

关于vb.net - 在 Using 语句中通过工厂创建一次性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36434665/

相关文章:

C# - 有没有理由不实例化一个类并在一行代码中使用它?

c# - 我应该使用 using 语句来创建 Windows.Forms.Form 对象吗?

vb.net - OpenGL 中的像素完美投影矩阵?

javascript - asp.net 服务器端禁用客户端启用的单选按钮

c# - 基于 Typeof 的工厂是一个

ruby-on-rails - 在rake任务中使用factory_girl-获取未初始化的常量

c# - .NET 标签中的文本格式

c# - Webkit.net 打开新标签页和窗口

具有多个构造函数签名的 C++ 通用工厂?

namespaces - 设置 ReSharper 将 'using' 导入放在命名空间之外