gpt4 book ai didi

c# - VB 与 C# : Why is this possible?

转载 作者:IT王子 更新时间:2023-10-29 04:30:39 26 4
gpt4 key购买 nike

这里有一些代码,每当我想到它时都会困扰我。

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, however, 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.

关于c# - VB 与 C# : Why is this possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26416644/

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