2014-03-30 185 views
0

我嘗試動態地將值(Test1)賦值給屬性(Wealth),以便根據初始化的類別計算出的值不同。但是我得到的結果都是0.誰能解釋我爲什麼以及如何解決問題。根據已初始化的類將屬性賦值給屬性

Public Class Class1 
    Private _test1 As Integer 

    Overridable ReadOnly Property Test1 As Integer 
     Get 
      Return _test1 
     End Get 
    End Property 

    Public ReadOnly Property Wealth As Integer 
     Get 
      Dim rnd As New Random 
      Dim val As Integer = rnd.Next(1, 6) 
      Return val * _test1 
     End Get 
    End Property 

End Class 

Public Class Class2 
    Inherits Class1 

    Public Overrides ReadOnly Property Test1 As Integer 
     Get 
      Return 3 
     End Get 
    End Property 

End Class 

初始化:

Public Class Form1 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Dim t As New Class2 
     MsgBox(t.Wealth.ToString) 
    End Sub 
End Class 

回答

0

不要使用私有變量,你需要引用屬性本身。

Public Class Form1 
    Public Class Class1 

    Overridable ReadOnly Property Test1 As Integer 
     Get 
     Return 0 'Default value' 
     End Get 
    End Property 

    Public ReadOnly Property Wealth As Integer 
     Get 
     Dim rnd As New Random 
     Dim val As Integer = rnd.Next(1, 6) 
     Return val * Test1 'Changed! Uses the Property name, so that if it is overridden it uses the new version' 
     End Get 
    End Property 

    End Class 

    Public Class Class2 
    Inherits Class1 

    Public Overrides ReadOnly Property Test1 As Integer 
     Get 
     Return 3 
     End Get 
    End Property 

    End Class 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim t As New Class2 
    MsgBox(t.Wealth.ToString) 
    End Sub 

End Class 
+0

偉大,exactely我一直在尋找,我甚至明白爲什麼它不適用於我的情況。乾杯! – ruedi

+0

嗨!第一部分工作,但現在在家裏,我看到「返回val * Test1」仍然是私有變量。所以這是行不通的。 – ruedi

+0

哪個地方值? 「VAL」?這是您的原始代碼中的本地定義的隨機數。你真的想用這個代碼做什麼?是否需要一款遊戲?因爲目前,每次使用「財富」功能時都會返回不同的值。 – SSS

0

聽起來像是你需要一個構造函數。

Public Class Class1 
Public Sub New(int As Integer) 
    Me.test1 = int 
End sub 
... 

然後,當你把它聲明

Dim t As New Class1(5) 
MsgBox(t.Wealth.ToString) 
+0

我指的是http://stackoverflow.com/questions/2004381​​/overridable-constant的確認回答,並認爲有解決方法不使用構造函數或均勻恆定的解決方案。 – ruedi

+0

好的,跟隨你的心。不知道這與你的問題有什麼關係。 – OneFineDay