Private Function CreateEvaluator(ByVal Expression As String) As MethodInfoPlus
Dim RealExpression As String = Expression
Dim FunctionX As New Regex("(?<Function>\w)\s*=\s*")
Dim M As Match = FunctionX.Match(Expression)
If M.Success Then
If M.Groups("Function").Value.ToLower = "y" Then
EvaluateX = True
Else
EvaluateX = False
End If
Else
Throw New ArgumentException("Espressione non valida!")
End If
If Expression.IndexOf("=") > -1 Then
RealExpression = Expression.Remove(0, Expression.IndexOf("=") + 1)
End If
Dim Code As String = _
"Imports Microsoft.VisualBasic" & vbCrLf & _
"Imports System" & vbCrLf & _
"Imports System.Math" & vbCrLf & _
"Public Class Evaluator" & vbCrLf & _
" Public Function Evaluate(ByVal X As Single) As Single" & vbCrLf & _
" Return " & RealExpression & vbCrLf & _
" End Function" & vbCrLf & _
"End Class" & vbCrLf
If Not EvaluateX Then
Code = Code.Replace("X", "Y")
End If
Dim Parameters As New CodeDom.Compiler.CompilerParameters
With Parameters
.GenerateExecutable = False
.IncludeDebugInformation = True
.TempFiles.KeepFiles = True
.GenerateInMemory = False
#Else
.TreatWarningsAsErrors = True
.TempFiles.KeepFiles = False
.GenerateInMemory = True
#End If
.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
.ReferencedAssemblies.Add("System.dll")
End With
Dim Provider As New VBCodeProvider
Dim CompResults As CompilerResults = Provider.CompileAssemblyFromSource(Parameters, Code)
If CompResults.Errors.Count > 0 Then
Dim Msg As String = ""
For Each Err As CompilerError In CompResults.
Errors Msg
&= Err.
ToString & vbCrLf
Next
'MsgBox(Msg, MsgBoxStyle.Critical)
Throw New ArgumentException("Espressione non valida!")
Else
Dim Asm As Reflection.Assembly = CompResults.CompiledAssembly
Dim Evaluator As Object = Asm.CreateInstance("Evaluator")
Dim EvalMethod As Reflection.MethodInfo = Evaluator.GetType.GetMethod("Evaluate")
Dim Result As MethodInfoPlus
Result.Method = EvalMethod
Result.Target = Evaluator
Return Result
End If
End Function
Private Function Evaluate(ByVal Method As MethodInfoPlus, ByVal Value As Single) As Single
Dim Args() As Object = {Value}
Dim Result As Object = Method.Method.Invoke(Method.Target, Args)
Return CSng(Result)
End Function