【发布时间】:2014-06-20 21:01:30
【问题描述】:
我正在研究一个与 VB.NET 和多个通用接口相关的奇怪问题。我的类通过指定两个不同的泛型类型参数两次实现了泛型接口。为了找到该问题的解决方案(如下所列),我有一个想法,但找不到任何资源来看看这是否可行。
VB.NET Implement Mutliple Contravariant interface types
此处的 MSDN 文档:http://msdn.microsoft.com/en-us/library/d5x73970.aspx 解释了类型约束的使用,这很有帮助但并不完整(或者至少该语言不支持我想要的)。
通常将约束声明为:
Public Interface ICopiesFrom(Of TObject As Class)
Sub CopyFrom(ByVal data As TObject)
End Interface
但是假设我想排除一个可能的泛型类型参数,而不是限制到一个子集。
Public Sub Interface ICopiesFrom(Of TObject Not As SpecificBadType)
这个可以吗?
看起来像:How to call a generic method with type constraints when the parameter doesn't have these constraints? 是重复的,但我的问题有点不同,因为我想要编译时支持。
编辑:
这是一个示例用例(可能是这样的):
'Ideally, the interface would have a definition like this
Public Interface ICopiesFrom(Of TModel As Not ISecureType)
Sub CopyFrom(ByVal data As TModel)
End Interface
'Target type to exclude
Public Interface ISecureType
Property AccountValue As Decimal
Property AccountNumber As String
End Interface
Public Class AccountModel
Public Overridable Property AccountCreated As DateTime
Public Overridable Property ReferredBy As Guid
End Class
Public Class DetailedAccountModel
Inherits AccountModel
Implements ISecureType
Public Property AccountNumber As String Implements ISecureType.AccountNumber
Public Property AccountValue As Decimal Implements ISecureType.AccountValue
End Class
Public Class ProfileModel
Public Property UserName As String
Public Property EmailAddress As String
Public Property PhoneNumber As String
End Class
Public Class User 'Composite representation for a view
Implements ICopiesFrom(Of ProfileModel)
Implements ICopiesFrom(Of AccountModel)
Public Property UserName As String
Public Property EmailAddress As String
Public Property PhoneNumber As String
Public Property AccountCreated As DateTime
Public Property ReferredBy As Guid
Public Overridable Overloads Sub CopyFrom(ByVal data As ProfileModel) Implements ICopiesFrom(Of ProfileModel).CopyFrom
If data IsNot Nothing Then
Me.UserName = data.UserName
Me.EmailAddress = data.EmailAddress
Me.PhoneNumber = data.PhoneNumber
End If
End Sub
Public Overridable Overloads Sub CopyFrom(ByVal data As AccountModel) Implements ICopiesFrom(Of AccountModel).CopyFrom
If data IsNot Nothing Then
Me.AccountCreated = data.AccountCreated
Me.ReferredBy = data.ReferredBy
End If
End Sub
Public Function AccountAge() As Double
Return (DateTime.Now - AccountCreated).TotalDays
End Function
End Class
在上述场景中,我绝不希望有人能够将 DetailedAccountModel 传递给 User 类,这样它就永远不会“意外”显示出来,理想情况下这会在编译时被捕获。
以下任何一个都是可接受的答案:
- 一种完全实现此目的的方法
- 实现相同(或类似)结果的替代方法
- 确认我疯了,这是不可能的(当然有来源)。
【问题讨论】:
-
约束的要点是告诉编译器约束类型的成员(方法/属性/等)是有效的,所以你可以使用它们,所以简短的回答是否定的,不是方式你正在尝试使用它们。向我们展示您希望在两个不同约束的实现中做什么。
-
@ClickRick 我已经用示例用法更新了我的问题。
-
我认为不可能
-
@ClickRick:让
Foo<U,V>类型同时实现IFoo<U,V>和IFoo<V,U>怎么样?被禁止是因为U和V可能是同一类型,在这种情况下IFoo<U,V>和IFoo<V,U>将是同一类型但可能具有冲突的方法定义。
标签: .net vb.net generics type-constraints