为什么不能推断二元运算符中的公共类型?

Why can't common type in binary operator be inferred?

我从以下代码中收到编译器警告 "Cannot infer a common type; 'Object' assumed.":

Dim occurrence As CacheableDocumentOccurrence = _
    If(DirectCast(IdentityMap.GetItem(id), CacheableDocumentOccurrence),
        Function() As CacheableDocumentOccurrence
            Dim x = New CacheableDocumentOccurrence()
            IdentityMap.Add(x)
            Return x
        End Function)

为什么?

你的 If 声明 return 是 CacheableDocumentOccurrence 如果 GetItem(id) return 不是 Nothing,而是 return 是 Function(lambda 表达式)否则! 在这两种情况下,您都必须 return a CacheableDocumentOccurrence

Dim occurrence As CacheableDocumentOccurrence = DirectCast(IdentityMap.GetItem(id)
If occurrence  Is Nothing Then
    occurrence = New CacheableDocumentOccurrence()
    IdentityMap.Add(x)
End If 

请注意,您的函数不仅仅是一些代码周围的括号。无论如何它都不会被执行;相反,结果将是一个 AddressOf 函数。