vb.net - 如何创建仅适用于支持特定接口的类的泛型类?
问题描述
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。我不能。为什么?代码有什么问题?
为什么?
解决方案
它不起作用,因为它T
是一个类型,而不是一个实例。您需要有一个实例来引用mainKey
. 您可能想要a.Cache.mainKey
或cache1.mainKey
。
(如果你真的想要一些东西Shared
而不是附加到实例上的东西,不幸的是,没有一个好的方法可以做到这一点,因为它不受 .NET 支持,除非通过各种基于反射的方法,请参阅各种关于缺少“静态接口”多年来。)
推荐阅读
- python - 刮板中的 ThreadExecutorPool 提前退出不确定为什么作为此代码的同步版本可以正常工作
- python-2.7 - 如何将 Kivy 应用程序加载到我的 iPhone
- mysql - 我可以通过 https://localhost:1337 在内部发出 reactjs axios 请求吗?
- python - 查找数字列表的所有组合,而python中的对不相同
- angular - 错误 TS2571:对象的类型为“未知”。在角度
- c# - ImageGrabbed 事件没有受到 EmguCv 的影响
- bash - 从终端直接执行 docker 可以正常工作,但从 .sh 脚本内部执行时不行?
- sql - 获取帖子 ID 列表的评论时间戳(created_utc),其中他们在任何 2 个节点之间有共同的评论作者 - Reddit 数据集
- c# - 无法获取http响应内容
- ibm-doors - 如何在 IBM 门的两列中划分值