【问题标题】:How to get a base class method return type to be the subclass type?如何让基类方法返回类型成为子类类型?
【发布时间】:2010-12-19 13:55:13
【问题描述】:

我有一个复制函数,我想在子类中重写它以返回子类的类型。这是我的界面:

Public Interface IBase(Of T)
    Function Copy() As T
End Interface

Public Interface ICar
    Inherits IBase(Of ICar)
End Interface

Public Interface IToyota
    Inherits ICar
End Interface

这是我的课程。如您所见,当 Car 覆盖 Copy 它返回 ICar 这就是我想要的。但是当 Toyota 覆盖 Copy 时,它还希望返回 ICar 而不是 IToyota。如何编写返回 IToyota

Public MustInherit Class Base(Of T)
    Implements IBase(Of T)

    Protected MustOverride Function Copy() As T Implements IBase(Of T).Copy

End Class

Public Class Car
    Inherits Base(Of ICar)
    Implements ICar

    Protected Overrides Function Copy() As ICar
        Return Nothing  //'TODO: Implement Copy
    End Function
End Class

Public Class Toyota
    Inherits Car
    Implements IToyota

    Protected Overrides Function Copy() As IToyota Implements IToyota.Copy
        //'I want this to return IToyota, but gives me a compile error
    End Function

End Class

【问题讨论】:

    标签: .net vb.net generics inheritance interface


    【解决方案1】:

    当你重写一个方法时,你不能改变它的返回类型。你可以省略 overrides 关键字来代替它,但它当然不再是虚拟的了。

    这不是什么大问题,除非您尝试使用 ICar 引用将 Toyota 对象复制到 Toyota 引用:

    Dim a As IToyota = New Toyota()
    Dim b As IToyota = a.Copy() ' works
    
    Dim c As ICar = New Toyota()
    Dim d As IToyota = c.Copy() ' doesn't work
    

    【讨论】:

      【解决方案2】:

      取出 overrides 关键字

      注意:接口不能实现这个功能——你必须在那里实现它。接口仅“定义”该功能将存在。

      【讨论】:

        【解决方案3】:

        您不能覆盖某些内容并返回更具体的对象。如果你想这样做,你将需要使用 Shadows 关键字,但是它只会在你有一个实际的 Toyota 变量的情况下返回 IToyota,而不是如果你的变量是 Car 类型但包含一个 Toyota 对象。例如:

        Dim MyToyotaVariable as Toyota = New Toyota
        MyToyotaVariable.Copy() 'Returns IToyota
        
        Dim MyToyotaVariable as Car = New Toyota
        MyToyotaVariable.Copy() 'Returns ICar
        

        这是将方法隐藏在基类中的限制,但您可以使用相同的方法名称在派生类中返回更具体的对象的唯一方法。

        【讨论】:

          【解决方案4】:

          您可以使您的 ICar 界面更通用,如果我的 vb.net 代码没有达到标准,请道歉。

          Public Interface IBase(Of T)    
              Function Copy() As T
          End Interface
          
          Public Interface ICar(Of T)    
              Inherits IBase(Of T)
          End Interface
          
          Public Interface IToyota    
              Inherits ICar(Of IToyota)
          End Interface
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-05-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-08-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多