在VB.NET中执行作为String存储的代码

时间:2017-07-22 19:37:05

标签: string vb.net parsing runtime

我想知道如何将一部分代码存储在对象的字符串字段中,并在运行时将其转换为可执行代码。

我们说我上课了:

Public Class Car

Public m_IDCar As String
Public m_Brand As String
Public m_Description As String
Public m_Condition As String ' => here I need to store an If, or an If condition as a String, that will be executed at run-time.

End Class

然后是CommandButton1.Click()

时发生的代码
Dim  carList As List(Of Car)
Dim parameter as String

' here I create carList with data from a database, so for each car In the database I create its relative object, with its .m_IDCar, .m_Brand, .m_Description and .m_Condition, and add it to carList

parameter = TextBox1.Text ' => given in input by the user

For each car As Car in carList
    If (car.m_Condition = True) then  ' => here there must be something to do cause, as things are now, in car.m_Condition is stored a String, but I need to parse it in code that returns a boolean value and, if this value would be True, the code will enter in the If statement.
        'do something
     End If
Next

car.m_Condition的示例可能是:

car.m_Condition = "(car.m_Name=""BMW"" AND car.m_Description.Contains(parameter)) OR car.m_Brand=""AUDI"""

如果有人帮助我,我需要一些关于如何实施这种方法的提示。

TY!

编辑: 谢谢大卫,我已经看到了这个问题并且看起来很相似。我已经看到用户询问如何将整个If存储在一个字符串中:

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

(询问该问题的用户使用IIf)

对我来说,最好的方法是将条件存储在字符串中进行评估,也许是将值与另一个中的结果进行比较。所以,例如:

Dim condition As String = "(car.m_Name=""BMW"" AND car.m_Description.Contains(parameter)) OR car.m_Brand=""AUDI"""
Dim valueToCompareWith as String = "True"

以及以下If

If (car.m_Name=""BMW"" AND car.m_Description.Contains(parameter)) OR car.m_Brand=""AUDI"" = True) Then
'do something
End If

将成为:

If (condition = valueToCompareWith) Then '(conceptually, because in this form it's simply a String comparison that returns always False)
'do something
End If

EDIT2:

感谢Plutonix,我已经读过你对Getters and Setters的暗示,我还没有指明它,但我正在研究的背景要复杂得多。我已经做了一个非常简单的例子来解决这个问题,但是我使用了大量的对象,需要比较各种字段,并且对于每个比较,If中有不同的条件,具有不同的逻辑和不同类型的数据进行比较。

0 个答案:

没有答案