我有一个实现IWeightable的Entity类: Public Interface IWeightable Property WeightState As WeightStateEnd Interface 我有一个WeightCalculator类: Public Class WeightsCalculator Public Sub New(...) ... End Sub Public Sub Calculat
Public Interface IWeightable Property WeightState As WeightState End Interface
我有一个WeightCalculator类:
Public Class WeightsCalculator Public Sub New(...) ... End Sub Public Sub Calculate(ByVal entites As IList(Of IWeightable)) ... End Sub End Class
遵循这个过程:
>实例化实体集合
Dim entites As New List(Of Entity)
> Instantiate WeightsCalculator Dim
wc As New WeightsCalculator(…)
为什么我不能做wc.Calculate(实体)?我收到:
Unable to cast object of type
‘System.Collections.Generic.List1[mynameSpace.Entity]'
1[myNamespace.IWeightable]’.
to type
'System.Collections.Generic.IList
如果实体实现IWeightable,为什么这不可能?
这不起作用.假设您有一个不同的类,OtherEntity,它也将实现该接口.如果您的上述代码可以使用,则Calculate方法可以将OtherEntity的实例添加到您的实体列表中:
Dim entities As New List(Of Entity)() Dim weightables As List(Of IWeightable) = entities ' VB forbids this assignment! weightables.Add(New OtherEntity())
这是非法的.如果不是,实体(0)的内容是什么?
要使代码工作,请使用带约束的泛型方法:
Public Sub Calculate(Of T As IWeightable)(ByVal entites As IList(Of T)) ... End Sub