c#動態(tài)編譯執(zhí)行對象方法示例 運(yùn)用映射機(jī)制創(chuàng)建對象
C#是一種編譯型的語言,程序執(zhí)行,首先要經(jīng)過編譯器編譯,如何讓C#像一種腳本一樣,在要執(zhí)行的時候,進(jìn)行編譯,這里,我們可以用Microsoft.CSharp空間下的CSharpCodeProvider提供類,來達(dá)到動態(tài)編譯的效果。在這里,我新建一個控制臺程序,在Program.cs類里引用using System.CodeDom.Compiler;
using System.Reflection;using Microsoft.CSharp;三大命名空間
#region using directiry
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
#endregion
/*==============================================================================
*
* author:lichaoqiang@163.com
* link:http://my.oschina.net/lichaoqiang
*
*
* ============================================================================*/
namespace CodeDom
{
class Program
{
#region 主程序入口
/// <summary>
///主程序入口
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//1>實(shí)例化C#代碼服務(wù)提供對象
CSharpCodeProvider provider = new CSharpCodeProvider();
//2>聲明編譯器參數(shù)
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
try
{
//3>動態(tài)編譯
CompilerResults result = provider.CompileAssemblyFromSource(parameters, BuildCSharpCode());
if (result.Errors.Count > 0)
{
Console.Write("編譯出錯!");
}
//4>如果編譯沒有出錯,此刻已經(jīng)生成動態(tài)程序集LCQ.LCQClass
//5>開始玩C#映射
Assembly assembly = result.CompiledAssembly;
object obj = assembly.CreateInstance("LCQ.LCQClass");
Type type = assembly.GetType("LCQ.LCQClass");
//6>獲取對象方法
MethodInfo method = type.GetMethod("Sum");
object[] objParameters = new object[2] { 1, 5 };
int iResult = Convert.ToInt32(method.Invoke(obj, objParameters));//喚醒對象,執(zhí)行行為
Console.Write(iResult);
Console.Read();
}
catch (System.NotImplementedException ex)
{
Console.Write(ex.Message);
}
catch (System.ArgumentException ex)
{
Console.Write(ex.Message);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
#endregion
#region 生成代碼塊
/// <summary>
/// 生成代碼塊
/// </summary>
/// <returns></returns>
private static string BuildCSharpCode()
{
string fileName = AppDomain.CurrentDomain.BaseDirectory.Replace("Debug", string.Empty).Replace("Release", string.Empty) + "CodeFile.cs";
string strCodeDom = File.ReadAllText(fileName);
return strCodeDom;
}
#endregion
}
}
相關(guān)文章
C#實(shí)現(xiàn)炫酷啟動圖-動態(tài)進(jìn)度條效果
這篇文章主要介紹了基于C#實(shí)現(xiàn)炫酷啟動圖-動態(tài)進(jìn)度條 效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05
C#基于純數(shù)學(xué)方法遞歸實(shí)現(xiàn)貨幣數(shù)字轉(zhuǎn)換中文功能詳解
這篇文章主要介紹了C#基于純數(shù)學(xué)方法遞歸實(shí)現(xiàn)貨幣數(shù)字轉(zhuǎn)換中文功能,涉及C#針對字符串的遍歷、轉(zhuǎn)換與數(shù)學(xué)運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-02-02

