VB.Net: 防止在 For Each 上缩小转换

VB.Net: prevent Narrowing Conversion on For Each

简短回答:没有办法阻止这种情况

也许这个问题是重复的,但我没有找到任何解决方案,因为我不知道我应该搜索什么词:

Option Strict On
Option Explicit On

Public Class Fruit
    '... stuff
End Class

Public Class Apple
    Inherits Fruit
    '... stuff
End Class

Public Class FruitCart

    Private _fruits As New List(Of Fruit)

    Public Function GetFirstApple() As Apple
        Return Me._fruits(0) '... <-- Option Strict error
    End Function

    Public Function GetApples() As List(Of Apple)
        Dim result As New List(Of Apple)
        For Each A As Apple In Me._fruits '... Why no error?
            result.Add(A)
        Next
        Return result
    End Function

End Class

方法 GetFirstApple() 给我一个编译错误。这是我想要的行为。 方法 GetApples() 没有给我编译错误,导致 运行-时间错误。

为什么编译器允许对 For Each 进行强制转换,即使 Option Strict On 也是如此? 我希望编译器在 GetApples() 方法上给我一个编译错误。

我刚发现。没有办法阻止这种情况,如 For Each 页面上的“缩小转换”中所述:For Each documentation