C# 动态加载程序集
定义动态程序集
namespace DynamicAssembly
{ public class CodeDriver : MarshalByRefObject
{
private string prefix =
"using System;" +
"public static class Driver" +
"{" +
" public static void Run()" +
" {"; private string postfix =
" }" +
"}"; public string CompileAndRun(string input, out bool hasError)
{
//for (int i = 0; i < 10;i++ )
//{ Console.WriteLine(i); }
hasError = false;
string returnData = null; CompilerResults results = null;
using (var provider = new CSharpCodeProvider())
{
var options = new CompilerParameters();
options.GenerateInMemory = true; var sb = new StringBuilder();
sb.Append(prefix);
sb.Append(input);
sb.Append(postfix); results = provider.CompileAssemblyFromSource(options, sb.ToString());
} if (results.Errors.HasErrors)
{
hasError = true;
var errorMessage = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
errorMessage.AppendFormat("{0} {1}", error.Line, error.ErrorText);
}
returnData = errorMessage.ToString();
}
else
{
TextWriter temp = Console.Out;
var 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;
}
}
}
编写调用代码
namespace DynamicAssembly
{
public class CodeDriverInAppDomain
{
public string CompileAndRun(string code, out bool hasError)
{
AppDomain codeDomain = AppDomain.CreateDomain("CodeDriver"); CodeDriver codeDriver = (CodeDriver)
codeDomain.CreateInstanceAndUnwrap("DynamicAssembly",
"DynamicAssembly.CodeDriver"); string result = codeDriver.CompileAndRun(code, out hasError); AppDomain.Unload(codeDomain); return result;
} }
}
wpf 页面代码
<Window x:Class="DynamicAssembly.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="" Width="">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" MinWidth="" />
</Grid.ColumnDefinitions>
<TextBox x:Name="textCode" AcceptsReturn="True" AcceptsTab="True" Grid.Row="" Grid.Column="" Margin="" />
<Button Click="Compile_Click" Grid.Row="" Grid.Column="" Content="Compile and Run" Margin="5, 10, 5, 10" />
<TextBlock x:Name="textOutput" Grid.Row="" Grid.Column="" Grid.ColumnSpan="" Margin="" />
</Grid> </Window>
后台代码
private void Compile_Click(object sender, RoutedEventArgs e)
{
// var custom = new CustomClassDamain();
// string s = custom.CompileAndRun(); textOutput.Background = Brushes.White;
var driver = new CodeDriverInAppDomain();
bool isError;
textOutput.Text = driver.CompileAndRun(textCode.Text, out isError);
if (isError)
{
textOutput.Background = Brushes.Red;
} }
C# 动态加载程序集的更多相关文章
- C# 动态加载程序集dll (实现接口)
一.程序集(接口程序集):LyhInterface.Dll namespace LyhInterface { public interface ILyhInterface { void Run(); ...
- C#动态加载程序集(转)
C#动态加载程序集 今天在看网络上的一篇关于‘.NET应用自动部署窗体技术’.NET的自动部署技术构造在.NET框架之中,它使得应用程序能够通过HTTP连接从远程服 务器按需下载程序集.有了这个功能, ...
- .Net Core 通过依赖注入和动态加载程序集实现宿程序和接口实现类库完全解构
网上很多.Net Core依赖注入的例子代码,例如再宿主程序中要这样写: services.AddTransient<Interface1, Class1>(); 其中Interface1 ...
- C# 动态加载程序集信息
本文通过一个简单的实例,来讲解动态加载Dll需要的知识点.仅供学习分享使用,如有不足之处,还请指正. 在设计模式的策略模式中,需要动态加载程序集信息. 涉及知识点: AssemblyName类,完整描 ...
- Assembly.Load动态加载程序集而不占用文件 z
方式一:占用文件的加载 Assembly assembly = Assembly.Load(path); 用上面的方法可以动态的加载到dll,但是用这种方法加载到的dll一直到程序运行结束都是占用的d ...
- 应用程序域 System.AppDomain,动态加载程序集
一.概述 使用.NET建立的可执行程序 *.exe,并没有直接承载到进程当中,而是承载到应用程序域(AppDomain)当中.在一个进程中可以包含多个应用程序域,一个应用程序域可以装载一个可执行程序( ...
- C# 反射实现动态加载程序集
原文:https://blog.csdn.net/pengdayong77/article/details/47622235 在.Net 中,程序集(Assembly)中保存了元数据(MetaData ...
- 关于c#动态加载程序集的一些注意事项
Assembly下有LoadFile,LoadFrom等方法可以加载程序集. LoadFile只加载你给定路径的那个dll,LoadFrom会自动加载依赖的dll. 如:A依赖B,LoadFile(& ...
- asp.net动态加载程序集创建指定类的实例及调用指定方法
以下类中有三个方法: LoadAssembly:加载指定路径的程序集 GetInstance:根据Type动态获取实例,用泛型接到返回的类型 ExecuteMothod:执行实例中的指定方法 /// ...
随机推荐
- [转帖]删除一张大表时为什么undo占用空间接近原表两倍?
删除一张大表时为什么undo占用空间接近原表两倍? https://www.toutiao.com/i6736735016492990983/ 原创 波波说运维 2019-09-22 00:01:00 ...
- [转帖]nginx location配置详细解释
nginx location配置详细解释 http://outofmemory.cn/code-snippet/742/nginx-location-configuration-xiangxi-exp ...
- 平衡树B树B+树红黑树
二叉树与二叉查找树的操作是必须要熟练掌握的,接下来说的这些树实现起来很困难,所以我们重点去了解他们的特点. 一.平衡二叉查找树与红黑树 平衡树AVL:追求绝对的高度平衡,它具有稳定的logn的高度,因 ...
- Linux删除Tomcat中产生的所有log文件
#!/bin/bash #!/bin/bash #exact all log files #计算log文件个数log_number=`ls *.log |grep log -c` #当log文件数大于 ...
- CentOS 7.X 静默安装Oracle 12C数据库
环境 System : CentOS 7.x jrxxfwb-zrgldb://> uname -a Linux jrxxfwb-zrgldb 3.10.0-693.17.1.el7.x86_6 ...
- 菜鸡之NetCore 使用EF操作数据库 Oracle & Sqlserver (一)
摘要: 该篇文章主要记录netCore EFCore 如何操作Oracle和SqlServer 数据库,采用Codefirst方式创建数据库以及表. 一, 项目建立 项目采用DDD领域驱动设计模式[学 ...
- 数据库入门(mySQL):创建数据库
基于JetBrains DataGrip创建数据库.SQL语句创建数据库 MySQL数据库存储引擎和数据类型 创建数据库表及基本操作 导出数据库.删除数据库.导入数据库 一.基于JetBrains D ...
- 移动端适配flexible.js
npm install lib-flexible --save npm install px2rem-loader --save-dev
- python多线程与多进程异步事件框架
多线程简单实现 #!/usr/bin/env python # -*- coding: UTF-8 -*- import logging import queue import threading f ...
- pkg-config命令
返回已安装库文件的元信息 pkg-config读取.pc文件获取信息 基本思想 编译的时候-I指定头文件路径:-L指定库文件路径.这样做总感觉很麻烦 事先把库的位置信息等保存起来,需要的时候再通过特定 ...