定义动态程序集

  1. namespace DynamicAssembly
  2. {
  3.  
  4. public class CodeDriver : MarshalByRefObject
  5. {
  6. private string prefix =
  7. "using System;" +
  8. "public static class Driver" +
  9. "{" +
  10. " public static void Run()" +
  11. " {";
  12.  
  13. private string postfix =
  14. " }" +
  15. "}";
  16.  
  17. public string CompileAndRun(string input, out bool hasError)
  18. {
  19. //for (int i = 0; i < 10;i++ )
  20. //{ Console.WriteLine(i); }
  21. hasError = false;
  22. string returnData = null;
  23.  
  24. CompilerResults results = null;
  25. using (var provider = new CSharpCodeProvider())
  26. {
  27. var options = new CompilerParameters();
  28. options.GenerateInMemory = true;
  29.  
  30. var sb = new StringBuilder();
  31. sb.Append(prefix);
  32. sb.Append(input);
  33. sb.Append(postfix);
  34.  
  35. results = provider.CompileAssemblyFromSource(options, sb.ToString());
  36. }
  37.  
  38. if (results.Errors.HasErrors)
  39. {
  40. hasError = true;
  41. var errorMessage = new StringBuilder();
  42. foreach (CompilerError error in results.Errors)
  43. {
  44. errorMessage.AppendFormat("{0} {1}", error.Line, error.ErrorText);
  45. }
  46. returnData = errorMessage.ToString();
  47. }
  48. else
  49. {
  50. TextWriter temp = Console.Out;
  51. var writer = new StringWriter();
  52. Console.SetOut(writer);
  53. Type driverType = results.CompiledAssembly.GetType("Driver");
  54.  
  55. driverType.InvokeMember("Run", BindingFlags.InvokeMethod |
  56. BindingFlags.Static | BindingFlags.Public,
  57. null, null, null);
  58.  
  59. Console.SetOut(temp);
  60.  
  61. returnData = writer.ToString();
  62. }
  63.  
  64. return returnData;
  65. }
  66. }
  67. }

编写调用代码

  1. namespace DynamicAssembly
  2. {
  3. public class CodeDriverInAppDomain
  4. {
  5. public string CompileAndRun(string code, out bool hasError)
  6. {
  7. AppDomain codeDomain = AppDomain.CreateDomain("CodeDriver");
  8.  
  9. CodeDriver codeDriver = (CodeDriver)
  10. codeDomain.CreateInstanceAndUnwrap("DynamicAssembly",
  11. "DynamicAssembly.CodeDriver");
  12.  
  13. string result = codeDriver.CompileAndRun(code, out hasError);
  14.  
  15. AppDomain.Unload(codeDomain);
  16.  
  17. return result;
  18. }
  19.  
  20. }
  21. }

wpf 页面代码

  1. <Window x:Class="DynamicAssembly.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="MainWindow" Height="" Width="">
  5. <Grid>
  6. <Grid.RowDefinitions>
  7. <RowDefinition />
  8. <RowDefinition />
  9. </Grid.RowDefinitions>
  10. <Grid.ColumnDefinitions>
  11. <ColumnDefinition />
  12. <ColumnDefinition Width="Auto" MinWidth="" />
  13. </Grid.ColumnDefinitions>
  14. <TextBox x:Name="textCode" AcceptsReturn="True" AcceptsTab="True" Grid.Row="" Grid.Column="" Margin="" />
  15. <Button Click="Compile_Click" Grid.Row="" Grid.Column="" Content="Compile and Run" Margin="5, 10, 5, 10" />
  16. <TextBlock x:Name="textOutput" Grid.Row="" Grid.Column="" Grid.ColumnSpan="" Margin="" />
  17. </Grid>
  18.  
  19. </Window>

后台代码

  1. private void Compile_Click(object sender, RoutedEventArgs e)
  2. {
  3. // var custom = new CustomClassDamain();
  4. // string s = custom.CompileAndRun();
  5.  
  6. textOutput.Background = Brushes.White;
  7. var driver = new CodeDriverInAppDomain();
  8. bool isError;
  9. textOutput.Text = driver.CompileAndRun(textCode.Text, out isError);
  10. if (isError)
  11. {
  12. textOutput.Background = Brushes.Red;
  13. }
  14.  
  15. }

C# 动态加载程序集的更多相关文章

  1. C# 动态加载程序集dll (实现接口)

    一.程序集(接口程序集):LyhInterface.Dll namespace LyhInterface { public interface ILyhInterface { void Run(); ...

  2. C#动态加载程序集(转)

    C#动态加载程序集 今天在看网络上的一篇关于‘.NET应用自动部署窗体技术’.NET的自动部署技术构造在.NET框架之中,它使得应用程序能够通过HTTP连接从远程服 务器按需下载程序集.有了这个功能, ...

  3. .Net Core 通过依赖注入和动态加载程序集实现宿程序和接口实现类库完全解构

    网上很多.Net Core依赖注入的例子代码,例如再宿主程序中要这样写: services.AddTransient<Interface1, Class1>(); 其中Interface1 ...

  4. C# 动态加载程序集信息

    本文通过一个简单的实例,来讲解动态加载Dll需要的知识点.仅供学习分享使用,如有不足之处,还请指正. 在设计模式的策略模式中,需要动态加载程序集信息. 涉及知识点: AssemblyName类,完整描 ...

  5. Assembly.Load动态加载程序集而不占用文件 z

    方式一:占用文件的加载 Assembly assembly = Assembly.Load(path); 用上面的方法可以动态的加载到dll,但是用这种方法加载到的dll一直到程序运行结束都是占用的d ...

  6. 应用程序域 System.AppDomain,动态加载程序集

    一.概述 使用.NET建立的可执行程序 *.exe,并没有直接承载到进程当中,而是承载到应用程序域(AppDomain)当中.在一个进程中可以包含多个应用程序域,一个应用程序域可以装载一个可执行程序( ...

  7. C# 反射实现动态加载程序集

    原文:https://blog.csdn.net/pengdayong77/article/details/47622235 在.Net 中,程序集(Assembly)中保存了元数据(MetaData ...

  8. 关于c#动态加载程序集的一些注意事项

    Assembly下有LoadFile,LoadFrom等方法可以加载程序集. LoadFile只加载你给定路径的那个dll,LoadFrom会自动加载依赖的dll. 如:A依赖B,LoadFile(& ...

  9. asp.net动态加载程序集创建指定类的实例及调用指定方法

    以下类中有三个方法: LoadAssembly:加载指定路径的程序集 GetInstance:根据Type动态获取实例,用泛型接到返回的类型 ExecuteMothod:执行实例中的指定方法 /// ...

随机推荐

  1. Redis服务监控之RedisLive安装部署(亲测可用)

    一.Redis服务安装部署 1.redis安装(linux系统) 下载 https://redis.io/ 安装依赖 yum install gcc tcl 解压.编译.安装(make & m ...

  2. Windows Terminal Preview v0.7 Release

    Windows Terminal Preview v0.7 Release The following key bindings are included by default within this ...

  3. 某 游戏公司 php 面试题

    1.实现未知宽高元素的水平垂直居中,至少两种方法. <div, class="father"> <div class="son">< ...

  4. GoF 的 23 种设计模式的分类和功能

    1. 根据目的来分 根据模式是用来完成什么工作来划分,这种方式可分为创建型模式.结构型模式和行为型模式 3 种. 创建型模式:用于描述“怎样创建对象”,它的主要特点是“将对象的创建与使用分离”.GoF ...

  5. PHP正则 正向预查&反向预查

    了解正向预查&反向预查前,我们先要知道正则的2个函数:preg_match_all . preg_replace preg_match_all 可以看文章:点击查看 preg_replace ...

  6. (转)从0移植uboot (四) _点亮调试LED

    这一节主要讨论1个问题:点灯.点灯是实际开发中,特别是裸板开发中常见的调试手段,相当于主机开发中漫天飞舞的printf/printk.为了追踪程序的现场执行情况,很多时候我们都使用点一个灯的方法来进行 ...

  7. 在JAVA中如何获取当前源文件名以及代码的行号

    在最近经历中,遇见了这样一个问题,如何获取当前源文件名以及代码的行号,只是了解到C语言有预定义宏__FILE__.__LINE__,它们在预处理的时候都已经确定好了,但是在JAVA中应该怎么获取输出呢 ...

  8. 监听lsnrctl status查询状态报错linux error 111:connection refused

    报错现象 今天给客户一个单实例环境配置监听,创建正常,查询状态异常报错 tns tns tns linux error :connection refused 匹配MOS Starting TNS L ...

  9. codeforce 839d.winter is here

    题意:如果一个子序列的GCD为1,那么这个子序列的价值为0,否则子序列价值为子序列长度*子序列GCD 给出n个数,求这n个数所有子序列的价值和 题解:首先得想到去处理量比较少的数据的贡献,这里处理每个 ...

  10. R语言做逻辑回归

    前面写过一个多分类的逻辑回归,现在要做一个简单的二分类,用glm函数 导入csv格式如下: mydata<-read.csv("D://li.csv",header=T) c ...