4

我正在 VB.Net 中编写一些代码,我希望向同事展示(更不用说让自己更熟悉一点)各种设计模式 - 我遇到了 FactoryMethod 模式的问题。

这是我的代码:

Namespace Patterns.Creational.FactoryMethod

    ''' <summary>
    ''' This is the Factory bit - the other classes are merely by way of an example...
    ''' </summary>
    Public Class CarFactory
        ''' <summary>
        ''' CreateCar could have been declared as Shared (in other words,a Class method) - it doesn't really matter.
        ''' Don't worry too much about the contents of the CreateCar method - the point is that it decides which type
        ''' of car should be created, and then returns a new instance of that specific subclass of Car.
        ''' </summary>
        Public Function CreateCar() As Car
            Dim blnMondeoCondition As Boolean = False
            Dim blnFocusCondition As Boolean = False
            Dim blnFiestaCondition As Boolean = False

            If blnMondeoCondition Then
                Return New Mondeo()
            ElseIf blnFocusCondition Then
                Return New Focus()
            ElseIf blnFiestaCondition Then
                Return New Fiesta()
            Else
                Throw New ApplicationException("Unable to create a car...")
            End If

        End Function
    End Class

    Public MustInherit Class Car
        Public MustOverride ReadOnly Property Price() As Decimal
    End Class

    Public Class Mondeo Inherits Car

        Public ReadOnly Overrides Property Price() As Decimal
            Get
                Return 17000
            End Get
        End Property
    End Class

    Public Class Focus Inherits Car
        Public ReadOnly Overrides Property Price() As Decimal
            Get
                Return 14000
            End Get
        End Property
    End Class

    Public Class Fiesta Inherits Car
        Public ReadOnly Overrides Property Price() As Decimal
            Get
                Return 12000
            End Get
        End Property
    End Class

End Namespace

当我尝试编译它时,我在 CarFactory.CreateCar 中收到错误 (BC30311),告诉我它无法将 Fiesta、Mondeo 和 Focus 转换为 Car。我不明白问题出在哪里——它们都是 Car 的子类。

毫无疑问,我忽略了一些简单的事情。谁能发现它?

干杯,

马丁。

4

3 回答 3

4

Inherits行或使用:分隔类名和Inherits语句:

Public Class Mondeo
    Inherits Car
...


Public Class Focus
    Inherits Car
...


Public Class Fiesta
    Inherits Car
...
于 2010-09-12T10:00:14.597 回答
2

您的 Inherits 关键字必须在新行上。Microsoft 在他们的帮助和支持中记录了这一点。http://support.microsoft.com/kb/307222

更改 SavingsAccount 类定义如下,以便 SavingsAccount 从 Account 继承(注意 Inherits 关键字必须出现在新行上):

于 2010-09-12T10:03:30.670 回答
1

列表中的第一个错误只是行号最低的错误,它并不总是错误的实际原因。

在错误列表的下方,您将看到(在其他几个错误中)End of statement expected.在每个子类中还有三个错误。这是因为Class并且Inherits是单独的语句并且在单独的行中进行:

Public Class Mondeo
  Inherits Car

或者:

Public Class Mondeo : Inherits Car

当您修复这些错误时,这些类实际上继承自Car,并且您的代码可以正常工作。

于 2010-09-12T10:07:38.237 回答