动态代码执行:字符串->运行时代码VB.net [英] Dynamic code execution: String -> Runtime code VB.net

查看:228
本文介绍了动态代码执行:字符串->运行时代码VB.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to execute some code inside a string in runtime. I.E.

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

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

How do i run the code inside code string ?

推荐答案

正如@ElektroStudios所说-正确的方法是使用 CodeDom编译器,但这对于像这样简单的东西来说有点过分了。

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.

欺骗并利用 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)

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

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)")

这篇关于动态代码执行:字符串->运行时代码VB.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆