VBCode in C# runtime compiling

本文介绍了一种使用CodeDom在运行时动态编译数学表达式的实现方法。通过Visual Basic Code Provider,将字符串形式的数学表达式编译为可执行代码,并提供了一个具体的类`FuncXYCodeDomHelper`来演示整个过程。
using System;
using System.CodeDom.Compiler; 
using Microsoft.VisualBasic;
using System.Reflection;
using System.Text;

public class FuncXYCodeDomHelper
{
    Assembly assy;

  
object execInstance;
  MethodInfo method;
  
object[] parameters;
  
  
public string expression;
  
  
public FuncXYCodeDomHelper(string exp)
  { 
       expression 
= exp;
       
        
//Generate VB Code
        StringBuilder sb = new StringBuilder();
        
//sb.Append("Imports System/r/n");
        sb.Append("Imports System.Math/r/n");
        sb.Append(
"Namespace RuntimeNamespace/r/n");
        sb.Append(
"Class RuntimeClass/r/n");
        sb.Append(
"Public Function f(ByVal x As Double, ByVal y As Double) As Double/r/n");
        sb.Append(
"Return " + this.expression + "/r/n");
        sb.Append(
"End Function/r/n");
        sb.Append(
"End Class/r/n");
        sb.Append(
"End Namespace/r/n");

      
//Prepare CodeDom
        VBCodeProvider cp = new VBCodeProvider();
        CompilerParameters cparams 
= new CompilerParameters();
        cparams.GenerateInMemory 
= true;
        CompilerResults cresults 
= cp.CompileAssemblyFromSource(cparams, sb.ToString());
        
        sb
=null;
        
        
if(cresults.Errors.Count>0)
        {
            
throw new Exception("Compile error count : " + cresults.Errors.Count.ToString());
        }
        
else
        {
            assy 
= cresults.CompiledAssembly;
            execInstance 
= assy.CreateInstance("RuntimeNamespace.RuntimeClass");
            Type t 
= execInstance.GetType();
            method 
= t.GetMethod("f");
            parameters 
= new object[2];
        }
  }
  
  
~FuncXYCodeDomHelper()
  {
       method 
= null;
       parameters 
= null;
       execInstance 
= null;
       assy 
= null;
  }
   
  
public double func(double x, double y)
  {
       parameters[
0]=x;
       parameters[
1]=y;
       
return (double)method.Invoke(execInstance, parameters);
  }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值