如何把含c#代码的字符串变成代码指令?

apengcn 2005-04-04 11:01:08
如举个简单的例子,当然字符串的内容没那么简单
int i;
string code="i=10000";
//这里如何加一句转换语句把code的内容变成实际能编译的语句,使10000真的赋值给变量i
int j=i/10;
...全文
165 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
兔子-顾问 2005-04-04
  • 打赏
  • 举报
回复
学习学习。
SeeSunSet 2005-04-04
  • 打赏
  • 举报
回复
Private Function GetJedgement(ByVal Expression As String) As Boolean
Dim Comp As ICodeCompiler = New VBCodeProvider().CreateCompiler
Dim cp As CompilerParameters = New CompilerParameters
Dim _Compiled As Object = Nothing

cp.ReferencedAssemblies.Add("system.dll")
cp.ReferencedAssemblies.Add("system.data.dll")
cp.ReferencedAssemblies.Add("system.xml.dll")
cp.GenerateExecutable = False
cp.GenerateInMemory = True
'dim CodeBuilding as
Dim code As String
code = "Imports System " & vbCrLf & _
"Imports System.Data " & vbCrLf & _
"Imports System.Xml " & vbCrLf & _
"Public Class Judgement " & vbCrLf & _
" Public Function GetJude() as Object " & vbCrLf & _
" Return (" & Expression & ") " & vbCrLf & _
" End Function " & vbCrLf & _
"End Class "

Dim cr As CompilerResults = Comp.CompileAssemblyFromSource(cp, code.ToString())
Debug.Write(code.ToString)
If (cr.Errors.HasErrors) Then

Dim ErrorMessage As String

ErrorMessage = "编译错误:" & vbCrLf
Dim Err As CompilerError
For Each Err In cr.Errors
ErrorMessage = ErrorMessage & Err.ErrorText & vbCrLf
Next
Debug.WriteLine(ErrorMessage)
#If DEBUG Then
Stop
#Else
Throw New Exception("编译错误: " + ErrorMessage)
#End If
End If

Dim a As System.Reflection.Assembly = cr.CompiledAssembly
_Compiled = a.CreateInstance("Judgement")

Dim mi As MethodInfo = _Compiled.GetType().GetMethod("GetJude")
Return (CType(mi.Invoke(_Compiled, Nothing), Boolean))
End Function
'测试
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As String = "6"
Dim tmp As String = x & ">5 And " & x & "<10"
MsgBox(GetJedgement(InputBox("输入表达式:", , tmp)))
End Sub
LoveCherry 2005-04-04
  • 打赏
  • 举报
回复
http://www.cnblogs.com/lovecherry/archive/2005/03/25/125520.html
apengcn 2005-04-04
  • 打赏
  • 举报
回复
具体如何写反射,请给个例子好吗
真相重于对错 2005-04-04
  • 打赏
  • 举报
回复
使用反射
jialiang 2005-04-04
  • 打赏
  • 举报
回复
如果能写完整差不多就可以去写编译器了
syeerzy 2005-04-04
  • 打赏
  • 举报
回复
使用反射,不过真的完全实现起来够自己去写个编译器了
apengcn 2005-04-04
  • 打赏
  • 举报
回复
谢谢各位,可是这些方法还是有点问题,象我上面例子中的变量i无法传递到表达式中去啊
redant0 2005-04-04
  • 打赏
  • 举报
回复
http://www.cnblogs.com/lovecherry/archive/2005/03/25/125520.html

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧