【问题标题】:Is it possible to assign a ReadOnly variable in a child class?是否可以在子类中分配 ReadOnly 变量?
【发布时间】:2013-08-25 16:57:13
【问题描述】:


假设我有这个父类:

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



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

【问题讨论】:

    标签: vb.net inheritance readonly


    【解决方案1】:

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

    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
    

    【讨论】:

    • 嘿@Reed -- 是否可以在Child 中将变量作为参数传递给MyBase.New?我收到错误消息:Implicit reference to object under construction is not valid when calling another constructor.
    • @IanCampbell 检查我的编辑 - 这就是你的意思吗?但是,您不能在那里使用Me.... 变量,因为尚未创建对象。您可以使用共享变量...
    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多