加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 23:53:29 所属栏目:大数据 来源:网络整理
导读:这里有一些代码,每当我想到这件事时,都会让我烦恼。 Option Strict OnModule Module1 Sub Main() For Each i As Integer In New String() {"why","is","this","tolerated?"} ' compiles just fine. Next End SubEnd Module 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读