当前位置 : 主页 > 编程语言 > c语言 >

.net – 混乱 – 实现的接口需要强制转换?

来源:互联网 收集:自由互联 发布时间:2021-06-24
我有一个实现IWeightable的Entity类: Public Interface IWeightable Property WeightState As WeightStateEnd Interface 我有一个WeightCalculator类: Public Class WeightsCalculator Public Sub New(...) ... End Sub Public Sub Calculat
我有一个实现IWeightable的Entity类:

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]'
to type
'System.Collections.Generic.IList
1[myNamespace.IWeightable]’.

如果实体实现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
网友评论