我有一個CSharpCodeProvider
它需要一個類的代碼。在正在編譯代碼的項目中,我有一個接口。我想要編譯的代碼符合這個接口。CSharpCodeProvider符合接口
下面是我能想到的最簡單的例子來說明我的問題。我有兩個文件的項目:
的Program.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");
,但它沒有奏效。任何幫助,將不勝感激。
我想你需要在編譯時有相同的程序集。換句話說,'csc /r:IDoc.dll dog.cs'是不合格的。 'csc dog.cs IDoc.cs'確定。 – BLUEPIXY
我並不完全遵循你所說的話。你可以進一步詳細一點嗎? – LandonSchropp
請看我的答案。 – BLUEPIXY