@@ -6,27 +6,16 @@ namespace DynamicCode.Compiler;
66
77public class SimpleDynamicCompiler
88{
9- public static Func < int , int , int > CompileFunction ( string body )
9+ public static T CompileFunction < T > ( string code , string className , string methodName ) where T : Delegate
1010 {
11- // Source code for a class with a static method Calculate
12- string code = $@ "
13- using System;
14- public static class DynamicClass
15- {{
16- public static int Calculate(int x, int y)
17- {{
18- { body }
19- }}
20- }}" ;
21-
2211 var syntaxTree = CSharpSyntaxTree . ParseText ( code ) ;
2312 var references = AppDomain . CurrentDomain . GetAssemblies ( )
2413 . Where ( a => ! a . IsDynamic && ! string . IsNullOrEmpty ( a . Location ) )
2514 . Select ( a => MetadataReference . CreateFromFile ( a . Location ) )
2615 . Cast < MetadataReference > ( ) ;
2716
2817 var compilation = CSharpCompilation . Create (
29- assemblyName : "DynamicAssembly" ,
18+ assemblyName : Constants . AssemblyName ,
3019 syntaxTrees : [ syntaxTree ] ,
3120 references : references ,
3221 options : new CSharpCompilationOptions ( OutputKind . DynamicallyLinkedLibrary )
@@ -42,9 +31,9 @@ public static int Calculate(int x, int y)
4231
4332 ms . Seek ( 0 , SeekOrigin . Begin ) ;
4433 var asm = Assembly . Load ( ms . ToArray ( ) ) ;
45- var type = asm . GetType ( "DynamicClass" ) ;
46- var method = type ! . GetMethod ( "Calculate" , BindingFlags . Public | BindingFlags . Static ) ;
34+ var type = asm . GetType ( className ) ;
35+ var method = type ! . GetMethod ( methodName , BindingFlags . Public | BindingFlags . Static ) ;
4736
48- return ( Func < int , int , int > ) method ! . CreateDelegate ( typeof ( Func < int , int , int > ) ) ;
37+ return ( T ) method ! . CreateDelegate ( typeof ( T ) ) ;
4938 }
5039}
0 commit comments