当type是值类型时,可以将null传递给泛型函数

问题描述 投票:0回答:1

我目前仅限于使用.NET 4.0使用VB.NET,我想在进行LINQ查询时使用预挂起函数,这是我创建的函数:

    <Extension>
    Public Iterator Function Prepend(Of TSource)(source As IEnumerable(Of TSource), item As TSource) As IEnumerable(Of TSource)
        If source Is Nothing Then Throw New ArgumentNullException(NameOf(source))

        Yield item
        For Each sourceItem In source
            Yield sourceItem
        Next
    End Function

但有趣的是当函数键入值类型时传递空引用,比如Integer:

Dim arr = {1, 2, 3}
Dim arr2 = arr.Prepend(Nothing).ToArray()

这将生成一个包含:0,1,2,3的数组。当转换为等效的C#并在.NET Core 2.1项目中使用时,我正确地收到编译器错误,告诉我无法在null和整数之间进行转换。

有没有办法告诉VB.NET我不希望发生这种事情并在编译时导致错误或者我是否需要求助于运行时类型检查?

vb.net generics .net-4.0
1个回答
2
投票

VB中的Nothing与C#中的null不同。更好的等价物是default,因为它代表了其类型的默认值。对于引用类型(其默认值为空引用),行为是相同的,但对于您注意到的值类型则非常不同。

由于这是语言设计的一部分,因此无法将其关闭。

另见Anthony Green的文章:https://anthonydgreen.net/2019/02/12/exhausting-list-of-differences-between-vb-net-c/#46

© www.soinside.com 2019 - 2024. All rights reserved.