3


假设我有这个父类:

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



我怎样才能做到这一点?如果不可能,为什么不呢?

4

1 回答 1

2

将它们传递给父构造函数:

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(s1 as String, s2 as String, s3 as String)
        str1 = s1
        str2 = s2
        str3 = s3
     End Sub
End Class

然后你的班级可以做:

Public Class Child
     Inherits Parent

     ' constructor:
     Public Sub New(s1 as String) ' You can pass these through if needed
          MyBase.New(s1, "qwerty", "foobar")
     End Sub
End Class
于 2013-08-22T19:35:57.970 回答