动态代码执行:字符串 - >运行时代码VB.net

时间:2016-03-24 12:18:07

标签: vb.net runtime clr eval vbc

我试图在运行时在字符串中执行一些代码。即。

Dim code As String = "IIf(1 = 2, True, False)"

如何在code字符串中运行代码?

1 个答案:

答案 0 :(得分:2)

正如@ElektroStudios所说 - 正确的方法是使用CodeDom compiler,但这对于像这样简单的事情来说有点过分。

你可以作弊并利用DataColumn Expression

的力量

例如:

    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)

您可以将所有这些包装成更通用的函数,如下所示:

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

那么你可以这样称呼它:

Dim result = EvaluateExpression(Of Integer, Boolean)(1, "IIF(Condition = 1, True, False)")