using System; using System.IO; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("namespace ConsoleApplication1"); sb.AppendLine("{"); sb.AppendLine(" public class MyScripter"); sb.AppendLine(" {"); sb.AppendLine(" public void Hello()"); sb.AppendLine(" {"); sb.AppendLine(" Console.WriteLine(\"Hello world!\");"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine("}"); // CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerResults compileResults = codeProvider.CompileAssemblyFromSource( new CompilerParameters(), new string[] { sb.ToString() }); // , foreach (CompilerError err in compileResults.Errors) Console.WriteLine("Error({0:1}): {2} {3}", err.Line, err.Column, err.ErrorNumber, err.ErrorText); if (compileResults.Errors.HasErrors) return; // dll byte[] dllBytes = File.ReadAllBytes(compileResults.PathToAssembly); Assembly asmDll = Assembly.Load(dllBytes, null); Type objType = asmDll.GetType("ConsoleApplication1.MyScripter"); // object oClassInst = Activator.CreateInstance(objType); // MethodInfo entry = objType.GetMethod("Hello", new Type[] {}); entry.Invoke(oClassInst, null); } } }
using System; using System.IO; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string sMyStr = "Before Script."; // StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("namespace ConsoleApplication1"); sb.AppendLine("{"); sb.AppendLine(" public class MyScripter"); sb.AppendLine(" {"); sb.AppendLine(" public void Hello(ref string s)"); sb.AppendLine(" {"); sb.AppendLine(" Console.WriteLine(\"Hello world!\");"); sb.AppendLine(" s=\"After Script.\";"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine("}"); // CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerResults compileResults = codeProvider.CompileAssemblyFromSource( new CompilerParameters(), new string[] { sb.ToString() }); // , foreach (CompilerError err in compileResults.Errors) Console.WriteLine("Error({0:1}): {2} {3}", err.Line, err.Column, err.ErrorNumber, err.ErrorText); if (compileResults.Errors.HasErrors) return; // dll byte[] dllBytes = File.ReadAllBytes(compileResults.PathToAssembly); Assembly asmDll = Assembly.Load(dllBytes, null); Type objType = asmDll.GetType("ConsoleApplication1.MyScripter"); // object oClassInst = Activator.CreateInstance(objType); // MethodInfo entry = objType.GetMethod("Hello", new Type[] { typeof(string).MakeByRefType() }); Object[] param = new Object[] { sMyStr }; Console.WriteLine(param[0]); // entry.Invoke(oClassInst, param); // Console.WriteLine(param[0]); // } } }
Source: https://habr.com/ru/post/327096/
All Articles