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");但它不起作用。任何帮助将不胜感激。
I have a CSharpCodeProvider
which takes in the code for a class. In the project where the code is being compiled, I have an interface. I would like the code I'm compiling to conform to this interface.
Here's the simplest example I could think of to illustrate my problem. I have a project with two files:
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();
}
}
I can't seem to figure out how to get the CSharpCodeProvider
to recognize IDog
. I tried compilerParameters.ReferencedAssemblies.Add("ConsoleApplication1");
but it didn't work. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案是引用当前正在执行的程序集。
The solution was to reference the currently executing assembly.
试试这个
try this
出色的!
可能是
Excellent!
It could be