内类工厂方法

时间:2015-02-27 13:36:10

标签: vb.net

我试图用技巧实现Factory方法,但由于某种原因无效:

Public Class MetamodelElement
Public Class MetamodelElementFactoryBase
End Class

Private Sub New()
End Sub

End Class

Public Class MetamodelElementFactory : Inherits MetamodelElement.MetamodelElementFactoryBase
    Function CreateMetamodelElement() As MetamodelElement
        Return New MetamodelElement()
    End Function

End Class

它表示该类无法访问私有方法(构造函数)。

我在这篇文章中关注了C#的一个例子: Hidden Features of C#?

1 个答案:

答案 0 :(得分:1)

编译器抱怨您正在尝试使用类外部的Private构造函数。这是不允许的。所以要么让它Public,要么不要叫它。

Public Class MetamodelElement
    Public Class MetamodelElementFactoryBase
    End Class

    Public Sub New()  ' <---- HERE!!! Now it works because it's public
    End Sub

End Class

Public Class MetamodelElementFactory
    Inherits MetamodelElement.MetamodelElementFactoryBase

    Function CreateMetamodelElement() As MetamodelElement
        Return New MetamodelElement() ' <--- HERE was the error
    End Function

End Class

您只能从类内部访问私有类成员。

MSDN: Access Levels


根据C# code that you've linked,您必须将构造函数移动到您继承的类中。然后您还可以使用Protected

Public Class MetamodelElement
    Public Class MetamodelElementFactoryBase
        Protected Sub New()
        End Sub
    End Class
End Class