用CodeDom、Reflection做一个简易计算器

原创 2004年08月04日 15:27:00

 

将代码粘贴到一个VB文件即可运行。我这里只是给出一种思路,按这种思路,可以做出一个强劲的计算器,也可以做出一个代码测试器或者是练习器。

 

Option Strict Off

Imports System.IO

Imports System.CodeDom.Compiler

Imports System.Reflection

 

Namespace LzmTW.Test

    Public Class frmCal

        Inherits System.Windows.Forms.Form

 

        Private Code As New CodeBuilder

        Private myMode As Mode

 

#Region " Windows 窗体设计器生成的代码 "

 

        Public Sub New()

            MyBase.New()

 

            '该调用是 Windows 窗体设计器所必需的。

            InitializeComponent()

 

            ' InitializeComponent() 调用之后添加任何初始化

 

        End Sub

 

        '窗体重写 dispose 以清理组件列表。

        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

            If disposing Then

                If Not (components Is Nothing) Then

                    components.Dispose()

                End If

            End If

            MyBase.Dispose(disposing)

        End Sub

 

        'Windows 窗体设计器所必需的

        Private components As System.ComponentModel.IContainer

 

        '注意: 以下过程是 Windows 窗体设计器所必需的

        '可以使用 Windows 窗体设计器修改此过程。

        '不要使用代码编辑器修改它。

        Friend WithEvents tbCode As System.Windows.Forms.TextBox

        Friend WithEvents tbResult As System.Windows.Forms.TextBox

        Friend WithEvents btnCal As System.Windows.Forms.Button

        Friend WithEvents tbReturnPara As System.Windows.Forms.TextBox

        Friend WithEvents Label1 As System.Windows.Forms.Label

        Friend WithEvents Label2 As System.Windows.Forms.Label

        Friend WithEvents tbSub As System.Windows.Forms.TextBox

        Friend WithEvents Label3 As System.Windows.Forms.Label

        Friend WithEvents Label4 As System.Windows.Forms.Label

        Friend WithEvents Button1 As System.Windows.Forms.Button

        Private Sub InitializeComponent()

            Me.tbCode = New System.Windows.Forms.TextBox

            Me.tbResult = New System.Windows.Forms.TextBox

            Me.btnCal = New System.Windows.Forms.Button

            Me.tbReturnPara = New System.Windows.Forms.TextBox

            Me.Label1 = New System.Windows.Forms.Label

            Me.Label2 = New System.Windows.Forms.Label

            Me.tbSub = New System.Windows.Forms.TextBox

            Me.Label3 = New System.Windows.Forms.Label

            Me.Label4 = New System.Windows.Forms.Label

            Me.Button1 = New System.Windows.Forms.Button

            Me.SuspendLayout()

            '

            'tbCode

            '

            Me.tbCode.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _

                        Or System.Windows.Forms.AnchorStyles.Left) _

                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)

            Me.tbCode.Location = New System.Drawing.Point(8, 32)

            Me.tbCode.Multiline = True

            Me.tbCode.Name = "tbCode"

            Me.tbCode.ScrollBars = System.Windows.Forms.ScrollBars.Both

            Me.tbCode.Size = New System.Drawing.Size(584, 72)

            Me.tbCode.TabIndex = 0

            Me.tbCode.Text = "'给定半径,求周长和面积" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "Dim M(3)" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "M(0)=20" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "M(1)=M(0)*Math.PI*2" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "M(2)=Math.PI*Math.Pow(M(0),2)" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "D" & _

            "im Result" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "Result=""半径:"" + M(0).Tostring +vbcrlf+""周长:"" + M(1).ToString+vbcrlf +""" & _

            ":"" +M(2).Tostring" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "        " & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "        " & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "'打开Excel" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "Dim oExcel As ExcelObj" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "oExcel" & _

            ".Open" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "oExcel.GetData(Result)"

            '

            'tbResult

            '

            Me.tbResult.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _

                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)

            Me.tbResult.Location = New System.Drawing.Point(8, 360)

            Me.tbResult.Multiline = True

            Me.tbResult.Name = "tbResult"

            Me.tbResult.ScrollBars = System.Windows.Forms.ScrollBars.Both

            Me.tbResult.Size = New System.Drawing.Size(584, 64)

            Me.tbResult.TabIndex = 1

            Me.tbResult.Text = ""

            '

            'btnCal

            '

            Me.btnCal.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)

            Me.btnCal.Location = New System.Drawing.Point(448, 320)

            Me.btnCal.Name = "btnCal"

            Me.btnCal.Size = New System.Drawing.Size(120, 32)

            Me.btnCal.TabIndex = 2

            Me.btnCal.Text = "计算(&C)"

            '

            'tbReturnPara

            '

            Me.tbReturnPara.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)

            Me.tbReturnPara.Location = New System.Drawing.Point(104, 112)

            Me.tbReturnPara.Name = "tbReturnPara"

            Me.tbReturnPara.Size = New System.Drawing.Size(152, 21)

            Me.tbReturnPara.TabIndex = 3

            Me.tbReturnPara.Text = "Result"

            '

            'Label1

            '

            Me.Label1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)

            Me.Label1.Location = New System.Drawing.Point(8, 112)

            Me.Label1.Name = "Label1"

            Me.Label1.Size = New System.Drawing.Size(72, 16)

            Me.Label1.TabIndex = 4

            Me.Label1.Text = "返回值参数"

            '

            'Label2

            '

            Me.Label2.Location = New System.Drawing.Point(8, 8)

            Me.Label2.Name = "Label2"

            Me.Label2.Size = New System.Drawing.Size(128, 16)

            Me.Label2.TabIndex = 5

            Me.Label2.Text = "主程序:"

            '

            'tbSub

            '

            Me.tbSub.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _

                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)

            Me.tbSub.Location = New System.Drawing.Point(8, 176)

            Me.tbSub.Multiline = True

            Me.tbSub.Name = "tbSub"

            Me.tbSub.ScrollBars = System.Windows.Forms.ScrollBars.Both

            Me.tbSub.Size = New System.Drawing.Size(584, 136)

            Me.tbSub.TabIndex = 6

            Me.tbSub.Text = "Class ExcelObj" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "   Private shared obj,Wb,Ws" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "   Public Shared Sub Open" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "       ob" & _

            "j=CreateObject(""Excel.Application"")" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "       obj.Visible = True" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "   End Sub" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "   P" & _

            "ublic Shared Sub GetData(Value)" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "       If Wb Is Nothing Then" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "          Wb=obj." & _

            "WorkBooks.Add " & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "          Ws=Wb.WorkSheets.Add" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "       End If" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "       Ws.Cells(1" & _

            ",1)=Value" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "   End Sub" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "End Class"

            '

            'Label3

            '

            Me.Label3.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)

            Me.Label3.Location = New System.Drawing.Point(8, 152)

            Me.Label3.Name = "Label3"

            Me.Label3.Size = New System.Drawing.Size(128, 16)

            Me.Label3.TabIndex = 7

            Me.Label3.Text = "函数:"

            '

            'Label4

            '

            Me.Label4.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)

            Me.Label4.Location = New System.Drawing.Point(8, 336)

            Me.Label4.Name = "Label4"

            Me.Label4.Size = New System.Drawing.Size(128, 16)

            Me.Label4.TabIndex = 8

            Me.Label4.Text = "结果:"

            '

            'Button1

            '

            Me.Button1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)

            Me.Button1.Location = New System.Drawing.Point(240, 320)

            Me.Button1.Name = "Button1"

            Me.Button1.Size = New System.Drawing.Size(120, 32)

            Me.Button1.TabIndex = 9

            Me.Button1.Text = "查看代码"

            '

            'frmCal

            '

            Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)

            Me.ClientSize = New System.Drawing.Size(600, 429)

            Me.Controls.Add(Me.Button1)

            Me.Controls.Add(Me.Label4)

            Me.Controls.Add(Me.Label3)

            Me.Controls.Add(Me.tbSub)

            Me.Controls.Add(Me.Label2)

            Me.Controls.Add(Me.Label1)

            Me.Controls.Add(Me.tbReturnPara)

            Me.Controls.Add(Me.btnCal)

            Me.Controls.Add(Me.tbResult)

            Me.Controls.Add(Me.tbCode)

            Me.Name = "frmCal"

            Me.Text = "简易代码计算器"

            Me.ResumeLayout(False)

 

        End Sub

 

#End Region

 

        Private Sub btnCal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCal.Click

            Code.Clear()

            Dim i As Int16

            For i = 0 To tbCode.Lines.Length - 1

                Code.AppendCode(2, tbCode.Lines(i))

            Next

            Code.AppendCode(2, "Return " & Me.tbReturnPara.Text)

            Code.AppendCode(1, "End Function")

            Code.AppendCode()

            For i = 0 To tbSub.Lines.Length - 1

                Code.AppendCode(2, tbSub.Lines(i))

            Next

            myMode = New Mode

            myMode.GetMode(Code.ToString)

            ' MsgBox(myMode.CodeString)

            Me.tbResult.Text = ""

            Me.tbResult.Text = myMode.CalResult

        End Sub

 

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

            If Not myMode Is Nothing Then

                Me.tbResult.Text = ""

                Me.tbResult.Text = myMode.CodeString

            End If

        End Sub

    End Class

    Public Class Mode

        Private Comp As ICodeCompiler = New VBCodeProvider().CreateCompiler

        Private cp As CompilerParameters = New CompilerParameters

        Private _Compiled As Object = Nothing

        Private mi As MethodInfo

        Private MyCode As CodeBuilder

        Public ReadOnly Property CodeString() As String

            Get

                Return MyCode.ToString

            End Get

        End Property 'CodeString

        Sub New()

        End Sub

        Sub GetMode(ByVal ModeString As String)

            MyCode = New CodeBuilder

            With MyCode

                .AppendCode("Imports System")

                .AppendCode("Imports System.Data")

                .AppendCode("Imports System.Math")

                .AppendCode("Imports Microsoft.VisualBasic")

                .AppendCode()

                .AppendCode("Public Class DealMode")

                .AppendCode("   Public Function GetM()")

                .AppendCode(ModeString)

                ' .AppendCode("   End Function")

                .AppendCode("End Class")

            End With

        End Sub 'GetMode

        Public Function CalResult() As Object

            cp.ReferencedAssemblies.Add("System.dll")

            cp.ReferencedAssemblies.Add("System.Data.dll")

            cp.ReferencedAssemblies.Add("System.Xml.dll")

            cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")

            cp.GenerateExecutable = False

            cp.GenerateInMemory = True

            'dim CodeBuilding as

            Dim code As String

            code = MyCode.ToString

 

            Dim cr As CompilerResults = Comp.CompileAssemblyFromSource(cp, code)

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

            mi = _Compiled.GetType().GetMethod("GetM")

            Return mi.Invoke(_Compiled, Nothing)

        End Function

 

    End Class 'Mode

    Public Class CodeBuilder

        Private _StringBuilder As System.Text.StringBuilder

        Private Const CodeFormat As String = "{0}{1}" & ControlChars.CrLf

        Sub New()

            _StringBuilder = New System.Text.StringBuilder

        End Sub

        Public Overloads Sub AppendCode()

            _StringBuilder.AppendFormat(CodeFormat, Space(0), Space(0))

        End Sub

        Public Overloads Sub AppendCode(ByVal CodeString As String)

            _StringBuilder.AppendFormat(CodeFormat, Space(0), CodeString)

        End Sub

        Public Overloads Sub AppendCode(ByVal CodeFloor As Integer, ByVal CodeString As String)

            _StringBuilder.AppendFormat(CodeFormat, Space(CodeFloor * 4), CodeString)

        End Sub

        Public Sub AppendFromFile(ByVal FileName As String)

            If Not System.IO.File.Exists(FileName) Then

                MsgBox(FileName & "不存在.")

                Exit Sub

            End If

            Dim tmpStr As String

            Dim fs As System.IO.FileStream

            fs = New System.IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)

            Dim Reader As New System.IO.StreamReader(fs, System.Text.Encoding.Default)

            tmpStr = Reader.ReadToEnd

            Reader.Close()

            fs.Close()

            _StringBuilder.Append(tmpStr)

        End Sub

        Public Overrides Function ToString() As String

            Return _StringBuilder.ToString

        End Function

        Public Sub Clear()

            If _StringBuilder.Length > 0 Then _StringBuilder.Remove(0, _StringBuilder.Length - 1)

        End Sub

    End Class 'CodeBuilder

End Namespace

 

JavaScript实现一个简易的计算器

JavaScript实现简易计算器的具体思路
  • sinat_27088253
  • sinat_27088253
  • 2016年07月18日 10:46
  • 2236

Java Swing做的简易计算器

先整了一个包 package cn.cal; 包里面有两个类: 一个 Calculator extends JFrame 实现计算器的界面 一个 Calculate 实现对算术表达式的处理 ...
  • tomorrowtodie
  • tomorrowtodie
  • 2016年10月30日 21:34
  • 947

如何用jsp实现一个简易计算器(三)

做这个jsp页面,主要是为了实现在同一个页面提交和接受数据的功能。 这个小程序存在很多不足,希望大家多多批评指正。...
  • believejava
  • believejava
  • 2014年09月08日 01:05
  • 5243

C# 一步一步完成一个简单的计算器 第一步---搭建计算器界面

这是本人第一篇文章谢谢大家关照,本人能力有限,麻烦大家轻喷. 正文开始 1.  创建项目 打开 Visual Studio(下文用VS 代替 Visual Studio ) , 文件->新建->项目....
  • yangdan3611925
  • yangdan3611925
  • 2015年10月27日 17:17
  • 9921

做一个iOS的简单计算器

这一段时间上班不那么忙,于是在github上开始了自己的新的工程,也是我接下来一年的一个小目标吧。作为一个数学爱好者,自然想到在项目内做一个计算器试试手感,首先在code4app上找了一个,感觉不好看...
  • u011238639
  • u011238639
  • 2017年02月22日 22:04
  • 719

基于Java实现的一个简单计算器

迷你计算器 本计算器能够实现基本的加减乘除四则运算。项目基于AWT和Swing,利用Java语言实现。JDK的版本是1.7。   运行界面:   代码: import java.awt.Borde...
  • haishangpiaobo2015
  • haishangpiaobo2015
  • 2017年03月31日 18:34
  • 756

Linearlayout编写一个计算器界面

Activity布局文件     xmlns:tools="http://schemas.android.com/tools"     android:orientation="vertica...
  • qq_27330089
  • qq_27330089
  • 2016年07月07日 19:21
  • 663

Qt实现简单计算器

Qt5.8实现计算器
  • tiantianfendou
  • tiantianfendou
  • 2017年03月24日 15:03
  • 2850

用JavaScript实现简单的计算器

html lang="en"> head> meta charset="UTF-8"> title>计算器title> link rel="stylesheet" type="...
  • baidu_25845567
  • baidu_25845567
  • 2016年06月09日 15:33
  • 458

用NetBeans编写计算器

NetBeans是开源软件开发集成环境,是一个开放框架,可扩展的开发平台,可以用于Java,C/C++,PHP等语言的开发,本身是一个开发平台,可以通过扩展插件来扩展功能。(摘自好搜百科)...
  • sunshinesky2
  • sunshinesky2
  • 2015年09月19日 11:05
  • 1436
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:用CodeDom、Reflection做一个简易计算器
举报原因:
原因补充:

(最多只允许输入30个字)