有人能用这个VB.Net代码发现问题吗?

时间:2010-09-12 09:54:04

标签: vb.net inheritance factory-method

我正在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的子类。

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

干杯,

马丁。

3 个答案:

答案 0 :(得分:4)

Inherits放在新行上,或使用:分隔班级名称和Inherits声明:

Public Class Mondeo
    Inherits Car
...


Public Class Focus
    Inherits Car
...


Public Class Fiesta
    Inherits Car
...

答案 1 :(得分:2)

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

  

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

答案 2 :(得分:1)

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

在错误列表中,您将看到(在其他几个错误中)另外三个错误,在每个子类中都会显示End of statement expected.。这是因为ClassInherits是单独的陈述,并且分开排列:

Public Class Mondeo
  Inherits Car

或:

Public Class Mondeo : Inherits Car

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