简体   繁体   English

VB.NET中的泛型

[英]Generics in VB.NET

Now, as a C# programmer, I know that generics are awesome. 现在,作为一名C#程序员,我知道泛型很棒。 However, when dabbling in some VB.NET, I discovered that the following does not cause a compiler error: 但是,当涉及到某些VB.NET时,我发现以下内容不会导致编译器错误:

Dim instance As List(Of Integer)
instance.Add(True)

Why is this? 为什么是这样? I know that you are not required to cast in VB.NET, but I'd have thought that this kills the main reason to use generics - type safety. 我知道你不需要使用VB.NET,但我认为这会杀死使用泛型的主要原因 - 类型安全。

Edit: I do not have option strict on, as this wasn't a real programming exercise, just me having a look at VB.NET in theory. 编辑:我没有严格的选项,因为这不是一个真正的编程练习,只是我在理论上看看VB.NET。 It is a theoretical question, as I was expecting it to cause a compiler error even with option strict off, just as a feature of generic types. 这是一个理论问题,因为我期望它甚至在选项严格关闭时导致编译器错误,就像泛型类型的一个特性一样。

Without Option Strict On , VB.NET is happy to implicitly convert Boolean to Integer . 如果没有Option Strict On ,VB.NET很乐意将Boolean隐式转换为Integer I strongly recommend (especially coming from a C# background) that you make Option Strict On the default for your VB.NET work. 我强烈建议(特别是来自C#背景)你做了Option Strict On你的VB.NET工作的默认值。

You can do this in Visual Studio in Tools | 您可以在Tools |中的Visual Studio中执行此操作 Options | Options | Projects and Solutions | Projects and Solutions | VB Defaults . VB Defaults

edit for more on the VB (classic) 'relaxed' attitude to type conversion, google 'Evil Type Coercion'. 编辑更多关于VB(经典)'轻松'的类型转换态度,谷歌'邪恶类型强制'。 Those of us who sought to do good work in VB (classic) had to wrestle this demon for while... 我们这些想要在VB(经典)中做好工作的人不得不摔跤这个恶魔......

你有Option Strict吗?

VB.NET converts at the function call site. VB.NET在函数调用站点转换。 The List(of Integer) is still storing an integer (-1, which is the integer value of True) List(of Integer)仍然存储一个整数(-1,它是整数值True)

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

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