是否需要指定公共函数的返回类型?

时间:2014-10-28 05:30:56

标签: vb.net function return return-value

我在这里有一个片段:

  Dim a As Integer = 10 '<--- an integer variable inintialized with 10
  a = byreferenceFun(a) '<---calling a function and assign the return value 

  Public Function byreferenceFun(ByVal a As Integer) '<-- function , no return type is specified
      byreferenceFun = 30 ' <-- return 30 to the calling function
 End Function

它们没有在函数中指定的返回类型,但它工作正常,returns整数和字符串值;

我的问题是指定Public Function的返回类型是否必要?或者是因为function that should return a value

的原因

2 个答案:

答案 0 :(得分:1)

来自:Function Statement (Visual Basic)

  

returntype - 如果选项严格 开启,则必填。值的数据类型   通过这个程序返回。

答案 1 :(得分:1)

在某种意义上你没有必要关闭选项严格,但是大多数人认为关闭选项严格是一种不好的做法(除非你当然知道你为什么要这样做......)

如果你决定关闭option strict并在你的函数上放弃as子句,那么你的函数将返回一个'Object',它是所有对象继承的基类,你可以将该对象强制转换为您要分配的类型。

唯一的问题是,如果你的函数返回一个对象,并且该对象的类型为“string”,那么当你将函数的输出分配给一个整数时,编译器在运行时才显示错误,那么你会获得无效的强制转换异常。

示例:

Sub Calculate()
    Dim result As Integer = GetCalculation()
End Sub
Function GetCalculation()
    Return "hello world"
End Function
相关问题