Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Why not use generic types? Define your class interface:</p> <pre><code> public interface IDynConcatenateString { string Concatenate(string s1, string s2); } </code></pre> <p>And then generate dinamic code</p> <pre><code> public T GetInstanceOf&lt;T&gt;(string code, string typename) { Console.WriteLine("Now doing some injection..."); Console.WriteLine("Creating injected code in memory"); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; //parameters.OutputAssembly = "DynamicCode.dll"; // if specified creates the DLL CompilerResults results = icc.CompileAssemblyFromSource(parameters, code); //type name = "CodeInjection.DynConcatenateString" T codeclass = (T)results.CompiledAssembly.CreateInstance(typename); return codeclass; } </code></pre> <p>Try to execute like this...</p> <pre><code>public void Exec() { string code = @" namespace CodeInjection { public class MyDynConcatenateString : IDynConcatenateString { public string Concatenate(string s1, string s2){ return s1 + "" ! "" + s2; } } }"; IDynConcatenateString writer = GetInstanceOf&lt;IDynConcatenateString&gt;( code, "CodeInjection.MyDynConcatenateString"); var s1 = Console.ReadLine(); var s2 = Console.ReadLine(); var result = writer.Concatenate(s1, s2); Console.WriteLine(result); } </code></pre> <p>The IDynConcatenateString implementation is dynamic, defined in the "code" variable, as a parameter of Exec method. You only need to define the interface, and no need to hardcode method names or class names.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload