Dynamic code execution: String -> Runtime code VB.net

▼魔方 西西 提交于 2019-12-05 19:13:04

As @ElektroStudios said - the proper way to do this is to use the CodeDom compiler, but this is a bit overkill for something as simple as this.

You can sort of cheat and harness the power of a DataColumn Expression

So for example:

    Dim formula = "IIF(Condition = 'Yes', 'Go', 'Stop')"
    Dim value As String = "Yes"
    Dim result As String

    'add a columns to hold the value
    Dim colStatus As New DataColumn
    With colStatus
        .DataType = System.Type.GetType("System.String")
        .ColumnName = "Condition"
    End With

    'add a column to compute the expression
    Dim colExp As New DataColumn
    With colExp
        .DataType = System.Type.GetType("System.String")
        .ColumnName = "Expression"
        .Expression = formula
    End With

    'create a table and add the columns
    Dim dt As New DataTable
    With dt.Columns
        .Add(colStatus)
        .Add(colExp)
    End With

    'now add a row and set the condition to the value we have
    Dim row As DataRow = dt.NewRow
    row.SetField(Of String)("Condition", value)
    dt.Rows.Add(row)

    'now read back the computed value based on the expression being evaluated
    result = row.Field(Of String)("Expression")
    MessageBox.Show(result)

You could wrap all this up into a more generic function like this:

Public Function EvaluateExpression(Of T, K)(input As T, formula As String) As K
    'add a columns to hold the value
    Dim colStatus As New DataColumn
    With colStatus
        .DataType = GetType(T)
        .ColumnName = "Condition"
    End With

    'add a column to compute the expression
    Dim colExp As New DataColumn
    With colExp
        .DataType = GetType(K)
        .ColumnName = "Expression"
        .Expression = formula
    End With

    'create a table and add the columns
    Dim dt As New DataTable
    With dt.Columns
        .Add(colStatus)
        .Add(colExp)
    End With

    'now add a row and set the condition to the value we have
    Dim row As DataRow = dt.NewRow
    row.SetField(Of T)("Condition", input)
    dt.Rows.Add(row)

    'now read back the computed value based on the expression being evaluated
    Return row.Field(Of K)("Expression")
End Function

So then you can call it like this:

Dim result = EvaluateExpression(Of Integer, Boolean)(1, "IIF(Condition = 1, True, False)")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!