Math Klasse in VB.Net

  • VB.NET

Es gibt 6 Antworten in diesem Thema. Der letzte Beitrag () ist von FatmaA.

    Math Klasse in VB.Net

    Hallo zusammen,

    ich habe eine Formel die wie folgt aussehen könnte.

    Dim Formel as string

    String = "Math.Cos(Math.Pow(10, 2)) + Pow(9, 1 / 3) + Math.PI"

    Diese ist als String gespeichert. Hintergrund ist, dass diese Formel über eine Oberfläche zusammengeklickt wird.

    Wie führe ich das nun aus.
    Wenn ich hingehe uns sage
    Dim Ergebnis as double

    Ergebnis = Formel

    funktioniert es nicht

    auch das funktioniert nicht
    Ergebnis = Double.Parse(Formel)

    Wie bekomme ich die Formel ausgewertet ??

    Vielen Dank im voraus

    Fatma
    @Counterbug Jou.

    FatmaA schrieb:

    Wie bekomme ich die Formel ausgewertet ?
    Da musst Du Dich allein drum kümmern.
    Vielleicht solltest Du davon die Finger lassen und Dich zunächst mit ein paar einfacheren Übungen befassen, gugst Du hier.
    Falls Du diesen Code kopierst, achte auf die C&P-Bremse.
    Jede einzelne Zeile Deines Programms, die Du nicht explizit getestet hast, ist falsch :!:
    Ein guter .NET-Snippetkonverter (der ist verfügbar).
    Programmierfragen über PN / Konversation werden ignoriert!
    So funktioniert es:

    _____________________________________________

    VB Code:
    Imports System.CodeDom.Compiler
    Imports Microsoft.VisualBasic 'More than just VB6 Runtime functions in here!
    Imports System.Reflection

    And here is the function, converted to VB.NETVB Code:
    ''' <summary>
    ''' A simple function using CodeDom to process an expression.
    ''' </summary>
    ''' <param name="command">A string expression to evaluate</param>
    ''' <returns>A double with the result of the evaluated command parameter</returns>
    ''' <remarks>Vulnerable to injection attacks.</remarks>
    Private Function ProcessCommand(ByVal command As String) As Double
    Dim MyProvider As New VBCodeProvider 'Create a new VB Code Compiler
    Dim cp As New CompilerParameters 'Create a new Compiler parameter object.
    cp.GenerateExecutable = False 'Don't create an object on disk
    cp.GenerateInMemory = True 'But do create one in memory.
    'If cp.OutputAssembly is used with a VBCodeProvider, it seems to want to read before it is executed.
    'See C# CodeBank example for explanation of why it was used.

    'the below is an empty VB.NET Project with a function that simply returns the value of our command parameter.
    Dim TempModuleSource As String = "Imports System" & Environment.NewLine & _
    "Namespace ns " & Environment.NewLine & _
    "Public Class class1" & Environment.NewLine & _
    "Public Shared Function Evaluate()" & Environment.NewLine & _
    "Return " & command & Environment.NewLine & _
    "End Function" & Environment.NewLine & _
    "End Class" & Environment.NewLine & _
    "End Namespace"
    'Create a compiler output results object and compile the source code.
    Dim cr As CompilerResults = MyProvider.CompileAssemblyFromSource(cp, TempModuleSource)
    If cr.Errors.Count > 0 Then
    'If the expression passed is invalid or "", the compiler will generate errors.
    Throw New ArgumentOutOfRangeException("Invalid Expression - please use something VB could evaluate")
    Else
    'Find our Evaluate method.
    Dim methInfo As MethodInfo = cr.CompiledAssembly.GetType("ns.class1").GetMethod("Evaluate")
    'Invoke it on nothing, so that we can get the return value
    Return Convert.ToDouble(methInfo.Invoke(Nothing, Nothing))
    End If
    End Function

    Sample usage and output:VB Code:
    MsgBox(ProcessCommand(TextBox1.Text)) 'SHows a message box with the result of an expression in TextBox1
    Console.WriteLine(ProcessCommand("1+1").ToString()) 'Displays 2
    Console.WriteLine(ProcessCommand("Math.PI").ToString()) 'Displays 3.14159265358979
    Console.WriteLine(ProcessCommand("Math.Abs(-22)").ToString()) 'Displays 22
    Console.WriteLine(ProcessCommand("3-4+6+7+22/3+66*(55)").ToString()) 'Displays 3649.333333333333333333

    _____________________________________

    Falls jemand sowas mal brauchen sollte.

    Grüße

    Fatma

    FatmaA schrieb:

    Falls jemand sowas mal brauchen sollte
    Gut recherchiert :thumbup: , aber unbrauchbar umgesetzt.
    Ich hab mir mal erlaubt, da was brauchbares zu machen:
    Parser

    VB.NET-Quellcode

    1. Imports System.CodeDom.Compiler
    2. Imports System.Reflection
    3. Public Class Parser
    4. ''' <summary>
    5. ''' A simple function using CodeDom to process an expression.
    6. ''' </summary>
    7. ''' <param name="command">A string expression to evaluate</param>
    8. ''' <returns>A double with the result of the evaluated command parameter</returns>
    9. ''' <remarks>Vulnerable to injection attacks.</remarks>
    10. Public Shared Function TryParseCommand(ByVal command As String, ByRef value As Double) As Boolean
    11. Dim MyProvider As New VBCodeProvider ' Create a new VB Code Compiler
    12. Dim cp As New CompilerParameters ' Create a new Compiler parameter object.
    13. cp.GenerateExecutable = False ' Don't create an object on disk
    14. cp.GenerateInMemory = True ' But do create one in memory.
    15. 'If cp.OutputAssembly is used with a VBCodeProvider, it seems to want to read before it is executed.
    16. 'See C# CodeBank example for explanation of why it was used.
    17. ' the below is an empty VB.NET Project with a function that simply returns the value of our command parameter.
    18. Dim TempModuleSource As String = "Imports System" & Environment.NewLine & _
    19. "Namespace ns " & Environment.NewLine & _
    20. "Public Class class1" & Environment.NewLine & _
    21. "Public Shared Function Evaluate()" & Environment.NewLine & _
    22. "Return " & command & Environment.NewLine & _
    23. "End Function" & Environment.NewLine & _
    24. "End Class" & Environment.NewLine & _
    25. "End Namespace"
    26. ' Create a compiler output results object and compile the source code.
    27. Dim cr As CompilerResults = MyProvider.CompileAssemblyFromSource(cp, TempModuleSource)
    28. If cr.Errors.Count > 0 Then
    29. 'If the expression passed is invalid or "", the compiler will generate errors.
    30. Return False
    31. End If
    32. 'Find our Evaluate method.
    33. Dim methInfo As MethodInfo = cr.CompiledAssembly.GetType("ns.class1").GetMethod("Evaluate")
    34. 'Invoke it on nothing, so that we can get the return value
    35. value = Convert.ToDouble(methInfo.Invoke(Nothing, Nothing))
    36. Return True
    37. End Function
    38. End Class

    VB.NET-Quellcode

    1. Public Class Form1
    2. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    3. Dim value As Double
    4. Parser.TryParseCommand("1+1", value) 'Displays 2
    5. Me.AppendText(value)
    6. Parser.TryParseCommand("Math.PI", value) 'Displays 3.14159265358979
    7. Me.AppendText(value)
    8. Parser.TryParseCommand("Math.Abs(-22)", value) 'Displays 22
    9. Me.AppendText(value)
    10. Parser.TryParseCommand("3-4+6+7+22/3+66*(55)", value) 'Displays 3649.333333333333333333
    11. Me.AppendText(value)
    12. End Sub
    13. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    14. Dim value As Double
    15. 'SHows a message box with the result of an expression in TextBox1
    16. If (Parser.TryParseCommand(TextBox1.Text, value)) Then
    17. Me.AppendText(value)
    18. Else
    19. Me.RichTextBox1.SelectionColor = Color.Red
    20. Me.RichTextBox1.AppendText("Fehler bei der Vorgabe der Formel" & Environment.NewLine)
    21. Me.RichTextBox1.SelectionColor = SystemColors.WindowText
    22. End If
    23. End Sub
    24. Private Sub AppendText(value As Double)
    25. Me.RichTextBox1.AppendText(value.ToString() & Environment.NewLine)
    26. End Sub
    27. End Class

    Parserklasse mit einem ordentlichen TryParseCommand und dem üblichen TryParse-Handling
    und zur Darstellung eine Form mit 2 Buttons und einer RichTextBox.
    Falls Du diesen Code kopierst, achte auf die C&P-Bremse.
    Jede einzelne Zeile Deines Programms, die Du nicht explizit getestet hast, ist falsch :!:
    Ein guter .NET-Snippetkonverter (der ist verfügbar).
    Programmierfragen über PN / Konversation werden ignoriert!