难以使用VB Code Dom(在生成的代码中使用If表达式)

时间:2009-11-27 08:09:07

标签: .net vb.net

我在使用vb代码dom时遇到了困难。基本上,我想动态编译这段代码:

Imports System    
Imports System.Collections.Generic
Imports Microsoft.VisualBasic
Namespace Formula

Public Class TsCalculator

Public Sub New()

End Sub

Public Shared Function Evaluate(ByVal Ts As Dictionary(Of String, Decimal)) As decimal

Dim result = If((Ts("sss")+Ts("zzz")) <> 0, (Ts("KWHD") - Ts("zzzz"))*Ts("sdsd")/(Ts("sds")+Ts("1ANGAT_M-DISPATCH")), (Ts("sdsd") - Ts("sdsd"))*(.5D + .5D))

Return result

End Function

End Class

End Namespace

为了编译这段代码,我使用了这个函数:

 Public Shared Function CompileCode(ByVal classname As String _

, ByVal inputname As String, _

ByVal compiler As CodeDomProvider, _

ByVal snippetcode As String) As Calculator(Of Decimal, Decimal)

Dim compilerargs = New CompilerParameters()

Dim code = BuildCodeString("Solver", inputname, snippetcode)

Dim currassembly = Reflection.Assembly.GetAssembly(GetType(FormulaCompiler))

With compilerargs

.TreatWarningsAsErrors = False

.ReferencedAssemblies.Add("System.dll")

.GenerateInMemory = True

.WarningLevel = 4

End With

Dim ss As Func(Of Dictionary(Of String, Decimal), Decimal)

Dim compiledresults = compiler.CompileAssemblyFromSource(compilerargs, code)

With compiledresults

If .Errors.HasErrors Then

Throw New InvalidExpressionException()

Else

Dim inputtypes = New Type() {GetType(Dictionary(Of String, Decimal))}

Dim formss = compiledresults.CompiledAssembly.GetType(String.Format("Formula.{0}", "Solver"))

Dim evalinfo = formss.GetMethod("Evaluate", inputtypes)

ss = CType([Delegate].CreateDelegate(GetType(Func(Of Dictionary(Of String, Decimal), Decimal)) _

, evalinfo), Func(Of Dictionary(Of String, Decimal), Decimal))

End If

End With

Dim calculator As New Calculator(Of Decimal, Decimal)(classname, ss)

Return calculator

End Function 

是否错过了一些装配?

干杯!

1 个答案:

答案 0 :(得分:0)

我终于找到了解决问题的方法。我最近发现,默认情况下,encodeom使用的是2.0编译器,而不是最新的编译器(.net 3.5的vb编译器)。您必须在创建VB编译器的实例时通过字典(字符串,sting)明确指定您将使用3.5 VB编译器...