Private Function GetJedgement(ByVal Expression As String) As Boolean
Dim Comp As ICodeCompiler = New VBCodeProvider().CreateCompiler
Dim cp As CompilerParameters = New CompilerParameters
Dim _Compiled As Object = Nothing
cp.ReferencedAssemblies.Add("system.dll")
cp.ReferencedAssemblies.Add("system.data.dll")
cp.ReferencedAssemblies.Add("system.xml.dll")
cp.GenerateExecutable = False
cp.GenerateInMemory = True
'dim CodeBuilding as
Dim code As String
code = "Imports System " & vbCrLf & _
"Imports System.Data " & vbCrLf & _
"Imports System.Xml " & vbCrLf & _
"Public Class Judgement " & vbCrLf & _
" Public Function GetJude() as Object " & vbCrLf & _
" Return (" & Expression & ") " & vbCrLf & _
" End Function " & vbCrLf & _
"End Class "
Dim cr As CompilerResults = Comp.CompileAssemblyFromSource(cp, code.ToString())
Debug.Write(code.ToString)
If (cr.Errors.HasErrors) Then
Dim ErrorMessage As String
ErrorMessage = "编译错误:" & vbCrLf
Dim Err As CompilerError
For Each Err In cr.Errors
ErrorMessage = ErrorMessage & Err.ErrorText & vbCrLf
Next
Debug.WriteLine(ErrorMessage)
#If DEBUG Then
Stop
#Else
Throw New Exception("编译错误: " + ErrorMessage)
#End If
End If
Dim a As System.Reflection.Assembly = cr.CompiledAssembly
_Compiled = a.CreateInstance("Judgement")
Dim mi As MethodInfo = _Compiled.GetType().GetMethod("GetJude")
Return (CType(mi.Invoke(_Compiled, Nothing), Boolean))
End Function
'测试
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As String = "6"
Dim tmp As String = x & ">5 And " & x & "<10"
MsgBox(GetJedgement(InputBox("输入表达式:", , tmp)))
End Sub