Confusion - does an implemented interface require casting?

I have an Entity class that implements IWeightable:

Public Interface IWeightable

    Property WeightState As WeightState

End Interface

I have a WeightCalculator class:

Public Class WeightsCalculator

    Public Sub New(...)
        ...
    End Sub

    Public Sub Calculate(ByVal entites As IList(Of IWeightable))
        ...
    End Sub

End Class

Following the process:

  • Create Entity Instance Dim entites As New List(Of Entity)
  • Activate WeightsCalculator Dim wc As New WeightsCalculator(...)

Why can't I execute wc.Calculate (entities)? I get:

Cannot start object of type 'System.Collections.Generic.List 1[mynameSpace.Entity]' to type 'System.Collections.Generic.IList1 [myNamespace.IWeightable]'.

If Entity implements IWeightable, why is this not possible?

+3
source share
2 answers

This does not work.

, OtherEntity, . , Calculate OtherEntity Entity:

Dim entities As New List(Of Entity)()
Dim weightables As List(Of IWeightable) = entities ' VB forbids this assignment!
weightables.Add(New OtherEntity())

. , entities(0)?

, :

Public Sub Calculate(Of T As IWeightable)(ByVal entites As IList(Of T))
    ...
End Sub
+6

A List(Of Entity) IList(Of IWeightable). ( OtherWeightable IWeightable):

Dim list As IList(Of IWeightable) = New List(Of Entity)
list.Add(new OtherWeightable)

- - OtherWeightable List(Of Entity).

.NET 4 . Calculate entities, :

Public Sub Calculate(ByVal entites As IEnumerable(Of IWeightable))

IList(Of T) , IEnumerable(Of T) T, API - T - T IEnumerable(Of T). , List(Entity) IEnumerable(Of IWeightable).

- - -2010 , . NDC 2010. ( "".)

.NET 3.5 , Konrad Calculate generic - .

+6

Source: https://habr.com/ru/post/1784958/


All Articles