【问题标题】:VB.Net does not throw compiler error when setting Dictionary to IList将 Dictionary 设置为 IList 时,VB.Net 不会引发编译器错误
【发布时间】:2011-07-06 20:10:18
【问题描述】:

我正在更新一个遗留应用程序,它正在从另一个项目中读取一个 dll 以获取项目的 Dictionary(of Guid, String) 并使用它们。

要求已更改,返回 Dictionary 的方法现在返回 IList。

这是 this 的奇怪行为;智能感知不会引发强制转换错误,编译器也不会。当它尝试将 Dictionary 设置为 IList 时,它直到运行时才会抛出错误。

例子:

        Dim someDictionary As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)
        Dim someList As IList(Of Integer)
        someDictionary = someList

知道为什么编译器没有捕捉到这个吗?

【问题讨论】:

  • 因为 VB.Net 不检查 类型安全 - 我从未认为 VB 是一种强类型语言。 VB 允许大量隐式转换,C# 在您尝试编译之前很久就会尖叫。
  • @IAbstract:启用 Option Explicit 和 Option Strict 后,VB 的类型非常强...
  • @Jon: 我想我是选项错了;)

标签: .net vb.net compiler-errors


【解决方案1】:

当“Option Strict”开启时会报错:

Option Strict On

Imports System.Collections.Generic

Public Class Test
    Public Shared Sub Main()
        Dim someDictionary As Dictionary(Of Integer, String) = _
               New Dictionary(Of Integer, String)
        Dim someList As IList(Of Integer) = Nothing
        someDictionary = someList
    End Sub
End Class

错误:

错误 BC30512:Option Strict On 不允许从 'System.Collections.Generic.IList(Of Integer)' 到 'System.Collections.Generic.Dictionary(Of Integer, String)' 的隐式转换。

   someDictionary = someList

我建议你更改你的项目以启用 Option Strict,以帮助捕捉这种事情:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2017-12-03
    相关资源
    最近更新 更多