简体   繁体   English

C#与VB.Net-隐式转换

[英]C# vs VB.Net - implicit conversions

This question is regarding implicit conversions in VB.Net and C#. 这个问题与VB.Net和C#中的隐式转换有关。 The following C# code does not compile: 以下C#代码无法编译:

class Program
{
    static void Foo(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        Foo(3); // Cannot convert from int to string
    }
}

The reason being that Foo expects a parameter of type string, but its given an int. 原因是Foo期望一个字符串类型的参数,但是给定一个int值。 A solution is to replace Foo(3) with Foo(3.ToString()) . 一种解决方案是将Foo(3)替换为Foo(3.ToString()) Fine. 精细。

Now, the same code authored in VB.Net: 现在,在VB.Net中编写的相同代码:

Module Module1
    Sub Foo(s As String)
        Console.WriteLine(s)
    End Sub

    Sub Main()
        Foo(5)
    End Sub
End Module

This compiles and runs just fine! 这样可以编译并正常运行!

Question: Why does VB.Net allow this and is there some fundamental difference between VB.Net and C# here? 问题:为什么VB.Net允许这样做,并且VB.Net和C#在这里有一些根本的区别?

Programming languages make different trade-offs. 编程语言会做出不同的权衡。 VB.NET with Strict=Off is very lax. Strict = Off的VB.NET非常宽松。 This is for historic compatibility reasons. 这是出于历史兼容性的原因。

A few decades ago programming language designers thought that this behavior was helpful to beginners. 几十年前,编程语言设计师认为这种行为对初学者很有帮助。 Now we know that such lax behavior is terrible for program correctness and development speed. 现在我们知道,这种松懈的行为对于程序的正确性和开发速度来说是可怕的。

JavaScript suffers from the same kind of problems, but worse. JavaScript遭受同样的问题,但是更糟。

Use strict semantics. 使用严格的语义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM