如何使用泛型覆盖派生类中的属性

时间:2017-08-18 14:11:51

标签: vb.net generics

我有以下课程设置,我不明白为什么它不会编译。

我在"公共覆盖属性F作为T"

  • ' Public Overrides Property F As T'不能覆盖'公共可覆盖财产F作为X'因为他们的回报类型不同。
  • 这让我感到困惑,因为我将T限制为从X派生。

有人可以解释我如何实现这一目标吗?最后,我需要有A类和B类,其中B继承自A.其中A具有类型X的可覆盖属性F,而B覆盖F,其类型派生自X.任何建议都值得赞赏。如果无法做到这一点,我有兴趣知道为什么(.NET的限制?)以及我应该怎么做。

Public Class X
End Class

Public Class Y
    Inherits X
End Class

Public Class A
    Public Overridable Property F As X
End Class

Public Class A(Of T As X)
    Inherits A
    Public Overrides Property F As T
End Class

Public Class B
    Inherits A(Of Y)
    Public Overrides Property F As Y
End Class

感谢 - 你!

2 个答案:

答案 0 :(得分:1)

新答案。我认为不可能(完全按照您的要求),即B overrides F with a type that is derived from X,如您所见。

但是你可以把Y放在B中的私有字段中并通过F公开它。然后你需要将F转换为Y来访问Y在X上提供的任何功能。这可以在不改变A的情况下完成。

Public Class X
    Public Overridable Function Z() As String
        Return "X"
    End Function
End Class

Public Class Y
    Inherits X
    Public Overrides Function Z() As String
        Return "Y"
    End Function
    Public Function Foo() As String
        Return "Bar"
    End Function
End Class

Public Class A
    Public Overridable Property F As X
End Class

Public Class B
    Inherits A
    Private _f As Y
    Public Overrides Property F As X
        Get
            Return _f
        End Get
        Set(value As X)
            _f = DirectCast(value, X)
        End Set
    End Property
End Class

用法:

Dim a As New A()
Dim x As New X()
Dim b As New B()
Dim y As New Y()

a.F = x
Console.WriteLine(a.F.Z)
' Console.WriteLine(DirectCast(a.F, Y).Foo()) ' InvalidCastException

b.F = y
Console.WriteLine(b.F.Z)
Console.WriteLine(DirectCast(b.F, Y).Foo()) ' OK

输出

  

X   
ÿ   
酒吧

答案 1 :(得分:0)

我终于找到了一个解决方案来完成我在使用Shadows关键字后所做的事情。

Imports System

Public Module Module1
    Public Sub Main()
        Dim a As New A()
        Dim b As New B()

        a.F = New X()
        b.F = New Y()

        Dim c As New Container()
        c.Value = a

        Console.WriteLine(c)        

        c.Value = b

        Console.WriteLine(c)        
    End Sub
End Module

Public Class Container
    Public Value As A
    Public Overrides Function ToString() AS String
        Return Value.ToString()
    End Function
End Class

Public Class X
    Public Overrides Function ToString() AS String
        Return "X"
    End Function
End Class

Public Class Y
    Inherits X
    Public Overrides Function ToString() AS String
        Return "Y"
    End Function
End Class


Public Class A
    Public Overridable Property F As X
    Public Overrides Function ToString() AS String
        Return "A" + F.ToString()
    End Function
End Class

Public Class B
    Inherits A
    Public Shadows Property F As Y
    Public Overrides Function ToString() AS String
        Return "B" + F.ToString()
    End Function
End Class