gpt4 book ai didi

vb.net - 动态代码执行 : String -> Runtime code VB.net

转载 作者:行者123 更新时间:2023-12-01 00:40:16 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于vb.net - 动态代码执行 : String -> Runtime code VB.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36200047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com