首页 > 解决方案 > 如何创建仅适用于支持特定接口的类的泛型类?

问题描述

Class cacheable(Of T As haveTimeStampandMainStringKey)
    Public ReadOnly Property Cache As T
    Public ReadOnly Property timestamp As Date

    Public Shared Function create(cache1 As T) As cacheable(Of T)
        Dim a = New cacheable(Of T)
        a._Cache = cache1
        a._timestamp = Now
        Dim key = T.mainkey 'this things fail to compile
        Return a
    End Function
End Class

Interface haveTimeStampandMainStringKey
    ReadOnly Property TimeStamp As DateTime
    ReadOnly Property mainKey As String
End Interface

基本上我希望类可缓存仅与支持 haveTimeStampandMainStringKey 的类一起使用

然而

Dim key = T.mainkey产生错误

显然 T 支持 haveTimeStampandMainStringKey 接口。所以我应该可以访问 T.mainkey。我不能。为什么?代码有什么问题?

为什么?

标签: vb.netgenerics

解决方案


它不起作用,因为它T是一个类型,而不是一个实例。您需要有一个实例来引用mainKey. 您可能想要a.Cache.mainKeycache1.mainKey

(如果你真的想要一些东西Shared而不是附加到实例上的东西,不幸的是,没有一个好的方法可以做到这一点,因为它不受 .NET 支持,除非通过各种基于反射的方法,请参阅各种关于缺少“静态接口”多年来。)


推荐阅读