编译器生成的 Reference.vb 文件中的 Option Strict Off

Option Strict Off in compiler generated Reference.vb file

是什么原因导致 vb.net 编译器将 Option Strict Off 添加到为 asmx Web 引用创建的 Reference.vb 文件中?有时有有时没有,而且似乎从来都没有必要。

由于该文件有一个 header 与此类似(您的版本号可能不同):

'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'     Runtime Version:4.0.30319.42000
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

第一个语句是:

Option Strict Off
Option Explicit On

我会说生成文件的工具正在使用 VBCodeProvider Class to produce the code using the CodeCompileUnit Class 并且该工具的作者没有覆盖 UserData 项目 AllowLateBoundRequireVariableDeclaration.

使用Reflector得到的Microsoft.VisualBasic.VBCodeGenerator.GenerateCompileUnitStart方法代码如下

Protected Overrides Sub GenerateCompileUnitStart(ByVal e As CodeCompileUnit)
    MyBase.GenerateCompileUnitStart(e)
    MyBase.Output.WriteLine("'------------------------------------------------------------------------------")
    MyBase.Output.Write("' <")
    MyBase.Output.WriteLine(SR.GetString("AutoGen_Comment_Line1"))
    MyBase.Output.Write("'     ")
    MyBase.Output.WriteLine(SR.GetString("AutoGen_Comment_Line2"))
    MyBase.Output.Write("'     ")
    MyBase.Output.Write(SR.GetString("AutoGen_Comment_Line3"))
    MyBase.Output.WriteLine(Environment.Version.ToString)
    MyBase.Output.WriteLine("'")
    MyBase.Output.Write("'     ")
    MyBase.Output.WriteLine(SR.GetString("AutoGen_Comment_Line4"))
    MyBase.Output.Write("'     ")
    MyBase.Output.WriteLine(SR.GetString("AutoGen_Comment_Line5"))
    MyBase.Output.Write("' </")
    MyBase.Output.WriteLine(SR.GetString("AutoGen_Comment_Line1"))
    MyBase.Output.WriteLine("'------------------------------------------------------------------------------")
    MyBase.Output.WriteLine("")
    If Me.AllowLateBound(e) Then
        MyBase.Output.WriteLine("Option Strict Off")
    Else
        MyBase.Output.WriteLine("Option Strict On")
    End If
    If Not Me.RequireVariableDeclaration(e) Then
        MyBase.Output.WriteLine("Option Explicit Off")
    Else
        MyBase.Output.WriteLine("Option Explicit On")
    End If
    MyBase.Output.WriteLine()
End Sub  

...

Protected Function AllowLateBound(ByVal e As CodeCompileUnit) As Boolean
   Dim obj2 As Object = e.UserData.Item("AllowLateBound")
   If ((Not obj2 Is Nothing) AndAlso TypeOf obj2 Is Boolean) Then
      Return CBool(obj2)
   End If
   Return True
End Function

Protected Function RequireVariableDeclaration(ByVal e As CodeCompileUnit) As Boolean
   Dim obj2 As Object = e.UserData.Item("RequireVariableDeclaration")
   If ((Not obj2 Is Nothing) AndAlso TypeOf obj2 Is Boolean) Then
      Return CBool(obj2)
   End If
   Return True
End Function