.Net Core - 源代碼動態編譯


源代碼的動態編譯問題,我們知道這個可以利用Roslyn來解決。
實現一個編譯助手類,它的Compile方法將會對參數sourceCode提供的源代碼進行編譯。該方法返回源代碼動態編譯生成的程序集,它的第二個參數代表引用的程序集。

添加Nuget包:

    <PackageReference Include="Microsoft.CodeAnalysis.Common" Version="3.7.0" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.7.0" />

編譯助手類:

public class Compiler
    {
        public Assembly Compile(string text, params Assembly[] referencedAssemblies)
        {
            var references = referencedAssemblies.Select(it => MetadataReference.CreateFromFile(it.Location));
            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var assemblyName = "_" + Guid.NewGuid().ToString("D");
            var syntaxTrees = new SyntaxTree[] { CSharpSyntaxTree.ParseText(text) };
            var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, references, options);
            using (var stream = new MemoryStream())
            {
                var compilationResult = compilation.Emit(stream);
                if (compilationResult.Success)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    return Assembly.Load(stream.ToArray());
                }
                throw new InvalidOperationException("Compilation error");
            }
        }
    }

動態編譯:

string code = @"public class Person
                            {
                                public static string SayName()=>""fan"";
                            }";
            var compiler = new Compiler();
            var assembly = compiler.Compile(code, Assembly.Load(new AssemblyName("System.Runtime")), typeof(object).Assembly);
            var personType = assembly.GetType("Person");
            if (personType != null)
            {
                var method = personType.GetMethod("SayName");
                var result = method.Invoke(null, null);// fan
            }

參考:https://www.cnblogs.com/artech/archive/2020/04/07/dynamic-controllers.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM