根据初始化的Class为属性赋值

时间:2014-03-30 18:38:31

标签: vb.net

我尝试动态地为属性(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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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