动态代码执行:将字符串转换为运行时代码 VB.net

4

我想在运行时执行一些字符串中的代码,例如:

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

我该如何运行 code 字符串里的代码?


请使用 CodeDom 编译器类。https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.vbcodeprovider(v=vs.110).aspx 我有一个包装器,您可以分析:https://github.com/ElektroStudios/ElektroKit/blob/master/Solution/v1.5/Elektro.Interop/Types/VisualBasicCompiler.vb 如果您只想评估算术表达式,则建议使用 NCalc 库:https://ncalc.codeplex.com/(因为 Microsoft 的 JS 评估器已被弃用)。此外,您应该使用 IF() 而不是 **IIF()**。 - ElektroStudios
谢谢。我想我会尝试使用CodeDom,使用这种方法:https://dev59.com/MHvaa4cB1Zd3GeqPHslX - Developer
1个回答

3
正如@ElektroStudios所说 - 正确的方法是使用CodeDom编译器,但对于像这样简单的事情来说有点过度杀伤力。
你可以有点作弊并利用DataColumn表达式的能力
所以,例如:
    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)")

2
使用数据列表达式是一种非常聪明的解决方案,我以前从未见过。感谢您分享这个。我注意到对于字符串,用户需要在条件中提供单引号而不是双引号。(**条件 = '字符串'**),我只是想评论一下,因为我曾经问过自己为什么双引号转义失败,然后我尝试了单引号。 - ElektroStudios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接