【问题标题】:Implementing an Interface with Child Classes使用子类实现接口
【发布时间】:2023-03-17 06:07:01
【问题描述】:

我有以下接口:

Interface IViewModel
    ...
End Interface

Interface ISpecialViewModel
    Inherits IViewModel
    ...
End Interface

Interface IView
    WriteOnly Property MyViewModel As IViewModel
End Interface

以下是我的课程:

Class VerySpecialViewModel
    implements ISpecialViewModel
    ...
End Class

Class View
    Implements IView

    Public WriteOnly Property MyViewModel As VerySpecialViewModel Implements IView.MyViewModel 
        ...
    End Property
End Class

它告诉我“MyViewModel”无法实现“MyViewModel”,因为接口“IView”上没有匹配的属性。

【问题讨论】:

    标签: vb.net oop interface inheritance


    【解决方案1】:
    Public Interface ISomething
        WriteOnly Property Prop As IParent
    End Interface
    

    您的类实现不满足该接口声明。考虑以下情况:

    还有另一个接口叫做 IChild2:

    Public Interface IChild2
        Inherits IParent
        ...
    End Interface
    

    根据ISomething接口,你应该能够将实现IChild2的类的实例分配给Thing.Prop,因为它继承了IParent。但是你不能,因为Thing.Prop属性是IChild类型和IChild2 不继承IChild

    更新

    那个解决方案怎么样:

    Class ThingBase
        Implements ISomething
    
        Public WriteOnly Property Prop As IParent Implements ISomething.Prop
            Set(value As IParent)
    
            End Set
        End Property
    End Class
    
    Class Thing
        Inherits ThingBase
    
        Public Overloads WriteOnly Property Prop As IChild
            Set(value As IChild)
                MyBase.Prop = value
            End Set
        End Property
    End Class
    

    更新2

    Interface IView(Of T As IViewModel)
        WriteOnly Property MyViewModel As T
    End Interface
    
    Class VerySpecialViewModel
        Implements ISpecialViewModel
    End Class
    
    Class View
        Implements IView(Of ISpecialViewModel)
    
        Public WriteOnly Property MyViewModel As ISpecialViewModel Implements IView(Of ISpecialViewModel).MyViewModel
            Set(value As ISpecialViewModel)
    
            End Set
        End Property
    End Class
    

    Class View
        Implements IView(Of VerySpecialViewModel)
    
        Public WriteOnly Property MyViewModel As VerySpecialViewModel Implements IView(Of VerySpecialViewModel).MyViewModel
            Set(value As VerySpecialViewModel)
    
            End Set
        End Property
    End Class
    

    【讨论】:

    • 嗯...我明白了。有没有优雅的解决方案?
    • 围绕什么?围绕实现接口而不满足其定义?不是真的。
    • 这是 MVVM。我基本上是在尝试在我的所有 ViewModel 上实现一个通用接口 IParent。其中一些 ViewModel 更专业并实现了 IChild。同样,我的 Views 也实现了一个通用接口 ISomething,它有一个成员 Prop 指向底层的 ViewModel 类。现在我不确定这个 Prop 在 ISomething 中是什么类型的?我的想法是让它成为 IParent 类型,以便所有视图都可以实现它。
    • 查看我的更新。您应该创建ThingBase 类或使用泛型。
    • 优秀的解决方案。唯一的问题是我的视图已经从一个框架类继承,而 vb.net 不允许多重继承。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2015-02-03
    • 2016-06-10
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多