How to convert string to code in vb.net and to vie

2019-08-14 05:36发布

问题:

Possible Duplicate:
How to expose current assembly to CodeProvider

I wrote a code which converts a string from a textbox in vb.net like in this exemple: how to convert string to code in c#

But In this class I can't call any static variables and methods from main project. That is code vb.net:

Dim vb As New VBCodeProvider()
Dim icc As ICodeCompiler = vb.CreateCompiler()
cp = New CompilerParameters
cp.ReferencedAssemblies.Add("System.dll")
cp.ReferencedAssemblies.Add("System.Windows.Forms.dll")
cp.ReferencedAssemblies.Add("System.Xml.dll")
cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
cp.ReferencedAssemblies.Add("Comatic(de-ch).exe")
cp.ReferencedAssemblies.Add("System.Data.dll")
cp.ReferencedAssemblies.Add("mscorlib.dll")
cp.CompilerOptions = "/t:library"
cp.GenerateInMemory = True
Dim sb As New StringBuilder("")

sb.Append("Imports System" & vbNewLine)
sb.Append("Imports Microsoft.VisualBasic" & vbNewLine)
sb.Append("Imports System.Windows.Forms" & vbNewLine)
sb.Append("Imports System.Xml" & vbNewLine)
sb.Append("Imports Comatic" & vbNewLine)
sb.Append("Imports System.Data" & vbNewLine)
sb.Append("<System.ComponentModel.ToolboxItem(False)> _" & vbNewLine)

sb.Append("Public Class VbCodeEvaler" & vbNewLine)
sb.Append("Public Sub EvalCode()" & vbNewLine)
sb.Append(TxVbCode.Text & vbNewLine)
sb.Append("End Sub" & vbNewLine)
sb.Append("Dim t As New System.Threading.Thread(AddressOf Me.EvalCode)" & vbNewLine) 'System.Threading.
sb.Append("Public Sub StartThred()" & vbNewLine)
sb.Append("t.Start()" & vbNewLine)
sb.Append("End Sub" & vbNewLine)
sb.Append("Public Sub StopThred()" & vbNewLine)
sb.Append("t.Abort()" & vbNewLine)
sb.Append("End Sub" & vbNewLine)
sb.Append("End Class" & vbNewLine)

cr = icc.CompileAssemblyFromSource(cp, sb.ToString())
If cr.Errors.Count > 0 Then
  MsgBox("Error: " & cr.Errors(0).ErrorText)
  Return Null
End If

Dim a As System.Reflection.Assembly = cr.CompiledAssembly
Dim o As Object = a.CreateInstance("VbCodeEvaler")
Dim t As Type = o.GetType()
'Dim mi As MethodInfo = t.GetMethod("EvalCode")
Dim mi As MethodInfo = t.GetMethod("StartThred")
mi.Invoke(o, Null)

How I can call all static and public methods and variables from main project? Thanks!

回答1:

If you are calling a static method in a module you need to explicitly define the module as public. Change:

Module Module1

to

Public Module Module1

You should be able to access any shared members of classes already