【发布时间】:2016-11-16 14:36:04
【问题描述】:
我最近在编写一些 vb.net 代码时遇到了我认为相当晦涩的语言功能。
特点是,如果你调用的函数没有接收到任何参数,而你试图用参数调用它(并且期望看到一个错误出现,或者至少得到一个编译时错误! ),它将被隐式转换为尝试索引函数的返回值。
以下代码示例来自在 Visual Studio 中创建的新 vb.net 表单项目。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Call GetCaption()
Me.Text = GetCaption() ' The caption of the form is 'this is my new form'
Me.Text = GetCaption(1) ' The caption of the form is 'h'
Me.Text = GetString(2) 'The caption of the form is '2'
End Sub
Private Function GetCaption() As String
Return "This is my new form"
End Function
Private Function GetString() As String()
Dim x As String() = {"", "0", "2"}
Return x
End Function
End Class
我发现以下文档提到“如果没有参数,您可以选择省略括号。但是,使用括号使您的代码更易于阅读。可在此处获取:https://msdn.microsoft.com/en-gb/library/1wey3ak2.aspx
我还找到了有关当您尝试使用具有无法在此处索引的返回类型的函数时收到的错误的文档:https://msdn.microsoft.com/en-us/library/y1wwy0we(v=vs.140).aspx
但是,我找不到任何讨论此功能的文档,或者提到隐式转换为索引函数返回的文档,而不是尝试将参数传递给不接收任何参数的函数。
有什么想法吗?
【问题讨论】:
-
返回是字符串。字符串是字符数组。所以
GetCaption(1)是该字符串中的第二个字符。如果该方法确实使用了 arg,GetCaption(arg)(1)也会这样做 -
例如相当于
Dim caption As String = GetCaption然后Me.Text = caption(1) -
(1)不是GetCaption的参数,它是从GetCaption返回的字符串的索引,因此您最终会使用 h。在您的GetString方法中,您将返回一个数组,因此(2)是该数组的索引。 -
能够在函数上省略括号的 VB 主义意味着
GetCaption()(1)会做同样的事情 -
@Plutonix 这将是一种明智的编写方式,因为任何阅读它的人都非常清楚。
GetCaption(1)可以被读者解释为传递一个参数,直到他们仔细查看该方法。