2015-08-28 44 views
1

如何在vb.net中調用基函數?來自VB.net的Child的調用函數

Imports System.Data.Sql 
Imports System.Data.SqlClient 

Public Class Box 
    Public length As Double ' Length of a box 
    Public breadth As Double ' Breadth of a box 
    Public height As Double ' Height of a box 
    Public function setLength(ByVal len As Double) 
     length = len 
    End Sub 
    Public Sub setBreadth(ByVal bre As Double) 
     breadth = bre 
    End Sub 
    Public Sub setHeight(ByVal hei As Double) 
     height = hei 
    End Sub 
    Public Function getVolume() As Double 
     Return length * breadth * height 
    End Function 
End Class 

它說語法錯誤,當我使用MyBase調用基函數

Public Class myChild : Inherits Box 
    'box 1 specification 
    MyBase.setLength(6.0) 
    MyBase.setBreadth(7.0) 
    MyBase.setHeight(5.0) 

    'box 2 specification 
    MyBase.setLength(12.0) 
    MyBase.setBreadth(13.0) 
    MyBase.setHeight(10.0) 

    'volume of box 1 
    volume = MyBase.getVolume() 
    Console.WriteLine("Volume of Box1 : {0}", volume) 

    'volume of box 2 
    volume = MyBase.getVolume() 
End Class 

回答

1

爲對象尚未建立不能從那裏調用MyBase

較好的實施方法是:

Box.vb

Public Class Box 
    Private mLength As Double ' Length of a box 
    Private mBreadth As Double ' Breadth of a box 
    Private mHeight As Double ' Height of a box 

    Public Sub New(ByVal length As Double, ByVal breadth As Double, ByVal height As Double) 
     Me.mLength = length 
     Me.mBreadth = breadth 
     Me.mHeight = height 

    End Sub 
    Public Property Length As Double 
     Get 
      Return Me.mLength 
     End Get 
     Set(ByVal value As Double) 
      Me.mLength = value 
     End Set 
    End Property 

Public Property Breadth As Double 
    Get 
     Return Me.mBreadth 
    End Get 
    Set(ByVal value As Double) 
     Me.mBreadth = value 
    End Set 
End Property 

Public Property Height As Double 
    Get 
     Return Me.mHeight 
    End Get 
    Set(ByVal value As Double) 
     Me.mHeight = value 
    End Set 
End Property 

Public Function getVolume() As Double 
    Return Length * Breadth * Height 
End Function 
End Class 

Child.vb

Public Class Child : Inherits Box 

    Public Sub New(ByVal length As Double, ByVal breadth As Double, ByVal height As Double) 
     MyBase.New(length, breadth, height) 
    End Sub 

End Class 

Sub Main() 
     Dim box1 As New Child(6.0, 7.0, 5.0) 
     Dim box2 As New Child(12.0, 13.0, 10.0) 

     Console.WriteLine("box1 volume is: {0}", box1.getVolume()) 
     Console.WriteLine("box2 volume is: {0}", box2.getVolume()) 
    End Sub 
+0

謝謝Bos!它真的解決了我的問題。 – Jesign

+0

嗯。所以在vb.net中,不需要使用include/require函數來使用其他文件?就像php使用include/require函數一樣。 – Jesign

+0

@ J.Ignacio如果所有文件都在同一個命名空間下,那麼您不需要顯式導入該文件。我的VB.NET非常棘手,但我認爲如果文件位於不同的名稱空間中,則需要導入 - 儘管VB對大部分內容都非常寬容。 – TEK