【问题标题】:Dynamic code execution: String -> Runtime code VB.net动态代码执行:字符串 -> 运行时代码 VB.net
【发布时间】:2016-07-12 00:50:48
【问题描述】:

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

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

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

【问题讨论】:

标签: vb.net runtime clr eval vbc


【解决方案1】:

正如@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)")

【讨论】:

  • 使用数据列表达式确实是我从未见过的聪明的解决方案。感谢分享这个。我注意到对于字符串,用户需要在条件中提供单引号而不是双引号。 (Condition = 'string'),我只是想评论一下,因为我问我为什么双引号转义失败,然后我尝试使用单引号。
猜你喜欢
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多