VB vs C#:为什么这可能?

前端之家收集整理的这篇文章主要介绍了VB vs C#:为什么这可能?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这里有一些代码,每当我想到这件事时,都会让我烦恼。
Option Strict On

Module Module1

    Sub Main()
        For Each i As Integer In New String() {"why","is","this","tolerated?"}
            ' compiles just fine.
        Next
    End Sub

End Module

C#根本不允许隐式转换为整数的字符串。

class Program {
    static void Main(string[] args) {
        foreach (int i in new string[] {"that's","better"}) {
            // will not compile,and for good reason.
        }
    }
}

为什么VB让我们这样做?我正在尝试这样玩乐,因为我在这里还是比较新的,但我也很好奇。我确定那里有开发商的答案。

这似乎是 For Each声明的特质。根据文档,它在运行时被评估。

链接

When Option Strict is set to On,narrowing conversions ordinarily cause compiler errors. In a For Each statement,however,conversions from the elements in group to element are evaluated and performed at run time,and compiler errors caused by narrowing conversions are suppressed.

In the following example,the assignment of m as the initial value for n doesn’t compile when Option Strict is on because the conversion of a Long to an Integer is a narrowing conversion. In the For Each statement,no compiler error is reported,even though the assignment to number requires the same conversion from Long to Integer. In the For Each statement that contains a large number,a run-time error occurs when ToInteger is applied to the large number.

原文链接:https://www.f2er.com/vb/256149.html

猜你在找的VB相关文章