在.NET中,强制转换实现接口是否会引起混乱?

2026-05-08 12:033阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计334个文字,预计阅读时间需要2分钟。

在.NET中,强制转换实现接口是否会引起混乱?

我有一个实现IWeightable接口的Entity类:plaintextPublic Interface IWeightable Property WeightState As WeightStateEnd Interface

我还有一个WeightCalculator类:plaintextPublic Class WeightCalculator Public Sub New(...)

End Sub

Public Sub Calculate(...) End Sub

我有一个实现IWeightable的Entity类:

Public Interface IWeightable Property WeightState As WeightState End Interface

我有一个WeightCalculator类:

在.NET中,强制转换实现接口是否会引起混乱?

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

本文共计334个文字,预计阅读时间需要2分钟。

在.NET中,强制转换实现接口是否会引起混乱?

我有一个实现IWeightable接口的Entity类:plaintextPublic Interface IWeightable Property WeightState As WeightStateEnd Interface

我还有一个WeightCalculator类:plaintextPublic Class WeightCalculator Public Sub New(...)

End Sub

Public Sub Calculate(...) End Sub

我有一个实现IWeightable的Entity类:

Public Interface IWeightable Property WeightState As WeightState End Interface

我有一个WeightCalculator类:

在.NET中,强制转换实现接口是否会引起混乱?

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