使用此代码......
Imports System.CodeDom.Compiler
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sb As New System.Text.StringBuilder
sb.AppendLine("Imports System")
sb.AppendLine("Imports System.Xml")
sb.AppendLine("Imports System.Data")
sb.AppendLine("Imports System.Collections.Generic")
sb.AppendLine("Namespace dValuate")
sb.AppendLine("Class EvalRunTime")
sb.AppendLine("Public Function EvaluateIt() As Object")
sb.AppendLine("{0}")
sb.AppendLine("End Function")
sb.AppendLine("End Class")
sb.AppendLine("End Namespace")
Dim testCode As String = "Dim d As Decimal = ""a"""
Dim provider As VBCodeProvider = New VBCodeProvider
Dim params As CompilerParameters = New CompilerParameters
Dim results As CompilerResults
params.ReferencedAssemblies.Add("system.dll")
params.ReferencedAssemblies.Add("system.xml.dll")
params.ReferencedAssemblies.Add("system.data.dll")
params.ReferencedAssemblies.Add("System.Windows.Forms.dll")
params.CompilerOptions = "/t:library"
params.GenerateInMemory = True
results = provider.CompileAssemblyFromSource(params, String.Format(sb.ToString, testCode))
sb.Length = 0
If results.Errors.Count > 0 Then
For Each err As CompilerError In results.Errors
sb.AppendLine("Line: " + err.Line.ToString + ", Error: " + err.ErrorText)
Next
MsgBox(sb.ToString)
End If
End Sub
End Class
当我尝试将小数设置为字符串时,为什么results.Errors.Count = 0?
有没有办法捕捉到这个错误?
答案 0 :(得分:0)
您需要Option Strict On
告诉VB编译器在编译时实际检查类型兼容性。
PS:考虑使用Roslyn而不是CodeDom。
答案 1 :(得分:0)
如果没有在严格模式下编译,则将字符串隐式转换为数字不是编译器错误。
将选项strict的开关添加到编译器选项:
params.CompilerOptions = "/t:library /optionstrict"