【问题标题】:Inherit and add properties to child class继承并添加属性到子类
【发布时间】:2014-11-04 04:19:06
【问题描述】:

我可以从一个类继承,并为我的新类添加属性...这一切都很好。

Class class1

 Property a as string

End Class

Class class2
 inherits class1

 property b as string

End Class

Dim mytest as new class2

mytest.a = "bleh"
mytest.b = "bah"

如何将属性添加到我正在继承的类中的子类?

Class class3

 Property a as string

 Class class3_1
   Property c as string
 End Class

End Class

如何创建一个继承 class3 的新类,但在我的新继承类中向 class3_1 添加一个属性?

带有实际非工作代码的新编辑

Public Class testclass

    Public Class class1

        Property x As String
        Property firstChildClass As New class1_1

        Public Class class1_1
            Property a As String
        End Class

    End Class

    Public Class inherited_class1
        Inherits class1

        Public Class class1_1  '///// Warning here to use "Shadows" keyword.. but that also does not work... takes away the warning, but still cant access property b when using a new instance of class
            Property b As String
        End Class

    End Class

    Sub test()

        Dim myTestClass As New inherited_class1

        myTestClass.firstChildClass.b = "blah" '///// This does not work...

    End Sub

End Class

【问题讨论】:

    标签: .net vb.net class oop inheritance


    【解决方案1】:

    只需在子类的继承中包含包含类。您必须分别继承包含类和子类:

    Public Class inherited_class1
        Inherits class1
    
        Public Class class1_2
            Inherits class1_1
            Public Property b() As String
        End Class
    
    End Class
    
    
    Public Sub test()
        Dim myTestClass As New inherited_class1()
    
        Dim ic As New inherited_class1.class1_2()
        myTestClass.firstChildClass = ic
        ic.b = "blah"
        '''//// This does not work...
    End Sub
    

    【讨论】:

    • 谢谢,我想我们在不同的页面上...我想继承父类及其所有属性,以及其中的所有其他子类...但是,我想要对与父类继承的“某些”子类进行更改
    • @LouisvanTonder:这次更新是不是更符合你的预期?
    • @LouisvanTonder:检查更新。我是一名 c# 程序员,所以我将它从 VB.NET 转换为 VB.NET。希望它对你有用。
    • 我认为的主要问题是子类和继承的子类之间的转换。由于您引用了基子类,因此您看不到该属性。
    • 好的,但是用不同的名称重新创建一个子类,并从其中继承,应该可以工作,但这会留下我的最终实例化与原始(基)子类以及新子类?
    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2015-08-11
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多