我有一个CSharpCodeProvider
,它接收类的代码。在编译代码的项目中,我有一个接口。我希望我正在编译的代码符合这个接口。
下面是我能想到的最简单的例子来说明我的问题。我有一个有两个文件的项目:
程序.cs:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//set up the compiler
CSharpCodeProvider csCompiler = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
var definition =
@"class Dog : IDog
{
public void Bark()
{
//woof
}
}";
CompilerResults results = csCompiler.CompileAssemblyFromSource(compilerParameters, new string[1] { definition });
IDog dog = null;
if (results.Errors.Count == 0)
{
Assembly assembly = results.CompiledAssembly;
dog = assembly.CreateInstance("TwoDimensionalCellularAutomatonDelegate") as IDog;
}
if (dog == null)
dog.Bark();
}
}
}
IDog.cs:
namespace ConsoleApplication1
{
interface IDog
{
void Bark();
}
}
我似乎不知道如何让CSharpCodeProvider
识别IDog
。我试过compilerParameters.ReferencedAssemblies.Add("ConsoleApplication1");
,但没用。如有任何帮助,我们将不胜感激。
解决方案是引用当前正在执行的程序集。
var location = Assembly.GetExecutingAssembly().Location;
compilerParameters.ReferencedAssemblies.Add(location);
尝试这个
using System;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//set up the compiler
CSharpCodeProvider csCompiler = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
compilerParameters.ReferencedAssemblies.Add("System.dll");
var definition = File.ReadAllText("./IDog.cs") +
@"public class Dog : ConsoleApplication1.IDog
{
public void Bark()
{
System.Console.WriteLine(""BowWoW"");
}
}";
CompilerResults results = csCompiler.CompileAssemblyFromSource(compilerParameters,
new string[1] { definition });
dynamic dog = null;
if (results.Errors.Count == 0)
{
Assembly assembly = results.CompiledAssembly;
// Type idog = assembly.GetType("ConsoleApplication1.IDog");
dog = assembly.CreateInstance("Dog");
} else {
Console.WriteLine("Has Errors");
foreach(CompilerError err in results.Errors){
Console.WriteLine(err.ErrorText);
}
}
if (dog != null){
dog.Bark();
} else {
System.Console.WriteLine("null");
}
}
}
}
太棒了!可能是
IDog dog = (IDog)a.CreateInstance("Dog");
dog.Bark(/*additional parameters go here*/);