1

I'm trying to compile a code at runtime and create an instance of one of the classes in it, but I get some errors when using c# 6+ features like string interpolation. Here is the code I'm using to compile:

        using (var cs = new CSharpCodeProvider())
        {
            var assembly = typeof(MyType).Assembly;
            var cp = new CompilerParameters()
            {
                GenerateInMemory = false,
                GenerateExecutable = false,
                IncludeDebugInformation = true,
            };

            if (Environment.OSVersion.Platform.ToString() != "Unix") cp.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
            else cp.TempFiles.KeepFiles = true;
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add(assembly.Location);
            CompilerResults cr;

            if (Directory.Exists(path))
            {
                string[] files = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
                cr = cs.CompileAssemblyFromFile(cp, files);
            }
            else cr = cs.CompileAssemblyFromFile(cp, new string[] { path });


            if (cr.Errors.HasErrors)
                throw new Exception("Compliation failed, check your code.");


            var types = cr.CompiledAssembly.GetTypes();
            var myType = types.Where(x => x.GetInterfaces().Contains(typeof(MyType))).FirstOrDefault();
            if (myType == null)
                throw new TypeLoadException("Could not find MyType class");

            return (MyType)cr.CompiledAssembly.CreateInstance(myType.FullName);

        }

Now if I try to compile a code that uses something like:

string name = $"My name is {name}";

I get this exception: Unexpected character '$'

4

1 回答 1

1

The fix to that problem was to use Microsoft.CodeDom.Providers.DotNetCompilerPlatform. And also I had to change the using Microsoft.CSharp to Microsoft.CodeDom.Providers.DotNetCompilerPlatform

see https://stackoverflow.com/a/40311406/34092 for more info

Many thanks to @mjwillis who helped me reach this solution.

于 2017-06-16T14:30:52.307 回答