gpt4 book ai didi

.net - 困惑 - 实现的接口(interface)需要强制转换?

转载 作者:行者123 更新时间:2023-12-01 07:46:31 25 4
gpt4 key购买 nike

我有一个实现 IWeightable 的实体类:

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)
  • 实例化权重计算器 Dim
    wc As New WeightsCalculator(...)

  • 为什么我不能做 wc.Calculate(entities)?我收到:

    Unable to cast object of type 'System.Collections.Generic.List1[mynameSpace.Entity]'
    to type
    'System.Collections.Generic.IList
    1[myNamespace.IWeightable]'.



    如果实体实现 IWeightable 为什么这不可能?

    最佳答案

    这不起作用。

    假设你有一个不同的类(class),OtherEntity ,这也将实现接口(interface)。如果上面的代码可以工作,方法 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

    关于.net - 困惑 - 实现的接口(interface)需要强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669292/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com