C#动态编译的小程序

using System;

using System.Text;

using System.Windows;

using System.Windows.Media;

using Microsoft.CSharp;

using System.CodeDom.Compiler;

using System.Reflection;

using System.IO;

namespace MyWpfApplication

{

/// <summary>

/// Interaction logic for MainWindow.xaml

/// </summary>

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void DynamicCompile_Click(object sender, RoutedEventArgs e)

{

CodeDriver driver = new CodeDriver();

bool isError;

outputTextBox.Text = driver.CompileAndRun(inputTextBox.Text, out isError);

if (isError)

{

outputTextBox.Background = Brushes.Red;

}

else

{

outputTextBox.Background = Brushes.White;

}

}

}

public class CodeDriver

{

private string prefix = "using System;" +

"public static class Driver" +

"{" +

"public static void Run()" +

"{";

private string postfix =

"}" +

"}";

public string CompileAndRun(string input, out bool hasError)

{

hasError = false;

string returnData = null;

CompilerResults results = null;

using (CSharpCodeProvider provider = new CSharpCodeProvider())

{

CompilerParameters options = new CompilerParameters();

options.GenerateInMemory = true;

StringBuilder sb = new StringBuilder();

sb.Append(prefix);

sb.Append(input);

sb.Append(postfix);

results = provider.CompileAssemblyFromSource(options, sb.ToString());

}

if (results.Errors.HasErrors)

{

hasError = true;

StringBuilder errorMessage = new StringBuilder();

foreach (CompilerError error in results.Errors)

{

errorMessage.AppendFormat("{0} {1}/n", error.Line, error.ErrorText);

}

returnData = errorMessage.ToString();

}

else

{

TextWriter temp = Console.Out;

StringWriter writer = new StringWriter();

Console.SetOut(writer);

Type driverType = results.CompiledAssembly.GetType("Driver");

driverType.InvokeMember("Run", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, null);

Console.SetOut(temp);

returnData = writer.ToString();

}

return returnData;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值