这里有新编码器,所以如果这是一个非常明显的问题我会提前道歉。我创建了一个名为IState的接口,IState的一个属性是Outputs,它是一个IStates列表。我计划有大约4个不同的类来实现IState接口。但是,在其中两个类中,我希望能够覆盖输出属性,并将其作为字符串列表,而不是IStates列表。这是可能的,还是有一种聪明的方法来解决它?
以下是IState的代码。
Public Interface IState
Property Name As String
Property Outputs As List(Of IState)
Property OnScreen As String
Sub Update()
Sub OnSpace()
End Interface
即使使用属性而不是字段,您所建议的内容也无法完成。如果您的接口声明了特定类型的成员,那么实现该接口的任何类型都必须实现该类型的该成员。你可以像这样使你的界面通用:
Public Interface IState(Of T)
Property Name As String
Property Outputs As List(Of T)
Property OnScreen As String
Sub Update()
Sub OnSpace()
End Interface
然后任何实现该接口的类都将指定T
本身。如果你想让T
成为那个界面你会遇到一个递归问题,所以我认为你可能只是运气不好。您基本上要求能够在不实现的情况下实现接口。答案是否定的,你做不到。
接口是属性,方法和事件及其签名(属性类型,方法参数顺序和类型等)的规范。您可以使用泛型作为动态定义新接口的方式,并且通用接口可以使用,但是您遇到的问题是IGeneric(Of Type1)
与IGeneric(OF Type2)
不同。
在了解除了您希望允许Outputs
属性为List(Of IState)
或List(Of String)
之外的特定使用要求时,很难设想一个通用的解决方案。
一个通用的解决方案是减少对Outputs
类型的约束,使其仅为IList。这将允许您返回List(Of IState)
或List(Of String)
。但是,实现也可以自由返回实现IList接口的任何其他类型。
Public Interface IState
Property Name As String
Property Outputs As IList
Property OnScreen As String
Sub Update()
Sub OnSpace()
End Interface
另一种方法是通过将Outputs
类型继承自IState
而没有Outputs
属性的新接口类型来保持对Public Interface IState
Property Name As String
Property OnScreen As String
Sub Update()
Sub OnSpace()
End Interface
Public Interface IOutputString : Inherits IState
Property Outputs As List(Of String)
End Interface
Public Interface IOutputIState : Inherits IState
Property Outputs As List(Of IState)
End Interface
类型的强大限制。
IState
这样做的好处是,您可以将实现上述任何接口的类实例作为qazxswpoi传递。如果需要访问Outputs属性,则可以尝试将值强制转换为IOutputXXXX类型之一。