3
假設我有這樣的父類:是否可以在子類中分配一個ReadOnly變量?
Public MustInherit Class Parent
' ReadOnly instance variables:
Protected ReadOnly str1 As String
Protected ReadOnly str2 As String
Protected ReadOnly str3 As String
' constructor:
Public Sub New()
End Sub
End Class
我想在子類的構造函數分配這些變量,我想他們是ReadOnly
,使他們無法改變分配一次,像這樣的:
Public Class Child
Inherits Parent
' constructor:
Public Sub New()
MyBase.New()
' can't assign the ReadOnly variables here!
' compile error: 'ReadOnly' variable cannot be the target of an assignment
Me.str1 = "asdf"
Me.str2 = "qwerty"
Me.str3 = "foobar"
End Sub
End Class
我怎樣才能做到這一點?如果不可能,爲什麼不呢?
啊哈,沒想到這,謝謝@Reed! –
嗨@Reed - 是否可以將一個變量作爲參數傳遞給'Child'中的MyBase.New?我收到錯誤:'調用另一個構造函數時,隱式引用正在構建的對象是無效的'。 –
@IanCampbell檢查我的編輯 - 是你的意思嗎?不過,你不能在那裏使用'Me ....'變量,因爲對象還沒有被創建。你*可以*使用共享變量... –