2017-07-07 50 views
2

當我創建我的Vehicle類的實例時,出現System.StackOverflowException。我相信這是因爲我有一個對象引用了我的Car類,該類繼承自Vehicle,並且它陷入了一個無限循環。System.StackOverflowException當創建類的實例

Public Class Vehicle 
    Public Car As New Car 
End Class 

Public Class Car 
    Inherits Vehicle 

    Public Sub doStuff() 
     'does stuff 
    End Sub 
End Class 

雖然可能是不好的做法,我有它的結構是這樣,因爲我需要能夠從另一個文件訪問doStuff(),而無需創建Car一個實例,像這樣:

'some other file 
Public Class Foo 
    Private Vehicle As New Vehicle 
    Vehicle.Car.doStuff() 'this is what I am trying to accomplish 
End Class 

是還有另一種方法可以實現這一目標?

編輯:由於似乎有一點混淆,我想澄清一下,我有多個繼承自車輛(汽車,卡車,自行車等)的類。所有這些類都有其獨特的方法,但都需要使用Vehicle的一些方法和屬性。使用virtual不是我正在尋找的,因爲我不需要重寫任何方法。

+0

汽車不應該實例化汽車類,它應該是相反的方式 – soohoonigan

+1

不知道「doStuff()」做了什麼,很難說,但「我需要能夠訪問'doStuff()'從另一個文件不需要創建一個'Car'的實例,通常可以通過將其設置爲Shared來解決 - 即'Public Shared Sub doStuff()'。然後你可以直接從'Foo'中的方法調用它:'Car.doStuff()'。 – Mark

+5

你不只是'有一個對象參考車類'車**創建**一個**新**車實例和車繼承車輛,因此無盡循環:車輛 - >車 - >車... – Plutonix

回答

4

好吧,我認爲這可能是你想要派生類的誤解。讓我用你的兩個類舉個例子:

Public Class Vehicle 
    Public Sub DoVehicleStuff() 
     ' code here 
    End Sub 
    Public Overridable Sub OverridableVehicleStuff() 
     'code here 
    End Sub 
End Class 

Public Class Car 
    Inherits Vehicle 

    Public Sub DoCarStuff() 
     'code here 
    End Sub 
    Public Overrides Sub OverridableVehicleStuff() 
     'code here 
    End Sub 
End Class 

好吧,車輛有兩個功能 - 其中之一是「重寫」,這意味着它的存在,但派生類可以覆蓋它。然後,Car從Vehicle繼承 - 這意味着它獲得相同的DoVehicleStuff()和OverridableVehicleStuff()。但是,它添加了一個附加函數DoCarStuff(),並用它自己的函數版本替換OverridableVehicleStuff。

全部放在一起,我們可以使用類這樣的:

Dim myVehicle As Vehicle = New Vehicle() 
myVehicle.DoVehicleStuff() 
myVehicle.OverridableVehicleStuff() ' does the VEHICLE version of the function 
'this will not compile: myVehicle.DoCarStuff() - because vehicles do not have that function. It is in the car sub-class. 

Dim myCarStoredInVehicle As Vehicle = New Car() 
myCarStoredInVehicle.DoVehicleStuff() 'I can still use this function - because Car inherited it 
myCarStoredInVehicle.OverridableVehicleStuff() 'this will do the CAR version of the function. 
'this will not compile: myCarStoredInVehicle.DoCarStuff() 

Dim myCar As Car = New Car() 
myCar.DoVehicleStuff() 'I can still call this function. 
myCar.DoCarStuff() 'and I can do the DoCarStuff() function, because the variable is a Car. 

因此,要回答你的問題:是所有車輛需要,或者只是汽車doStuff()的東西嗎?如果所有車輛都需要以某種方式進行操作,則需要編寫一個可覆蓋的(或抽象的)功能。如果它只是Cars使用的東西,那麼你不能爲你想要的東西使用Vehicle類實例。您需要以下選項之一:

  1. 將您的變量聲明爲汽車。
  2. 將您的變量聲明爲Vehicle,但將其實例化爲新的 Car()。然後當您需要使用DoStuff()時,將該變量作爲(Car)投射。

編輯:哎呀,OP是詢問VB,而不是C#。適當編輯代碼。

+0

問題是在VB中,這個答案是在C#中... –

+1

@Lews - 謝謝!我甚至沒有注意到這一點。我編輯了我的答案,將其更改爲vb.net – Kevin