[英]Compile at runtime with referenced assemblies
I have created a function to compile C# code in a string in memory and use it at runtime. 我创建了一个函数,用于在内存中的字符串中编译C#代码并在运行时使用它。 It works very well.
效果很好。
Next I created a small class library (lets call it mynew.dll) and placed it at c:\\mylibraries\\mynew.dll. 接下来,我创建了一个小型类库(将其称为mynew.dll),并将其放置在c:\\ mylibraries \\ mynew.dll中。
In my code I can add a referenced assembly. 在我的代码中,我可以添加一个引用的程序集。 I do it like this:
我这样做是这样的:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
parameters.ReferencedAssemblies.Add(@"c:\mylibraries\mynew.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, mycode);
Now, in my C# code-string (mycode) is a function called "Execute". 现在,在我的C#代码字符串(mycode)中是一个名为“ Execute”的函数。 When I declare the namespace and class from the mynew.dll in this function I get this error:
当我在此函数中从mynew.dll声明名称空间和类时,出现以下错误:
Could not load file or assembly 'MyNew, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.
无法加载文件或程序集“ MyNew,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”或其依赖项之一。 The system cannot find the file specified.
该系统找不到指定的文件。
When I copy the dll in the bin/debug folder of the main application is suddenly works, but I don't want this. 当我将dll复制到主应用程序的bin / debug文件夹中时,它突然起作用了,但我不希望这样做。 I want the code, that is compiled at runtime, to use it, not the main application.
我希望在运行时编译的代码使用它,而不是主应用程序。
This I did before posting here: 我在这里发布之前所做的:
Is there a way to fix this? 有没有办法解决这个问题?
Use Directory.GetFiles to find your assembly in the file system, use System.Reflection.Assembly.LoadFile to load the assembly, and then find the types required. 使用Directory.GetFiles在文件系统中找到您的程序集,使用System.Reflection.Assembly.LoadFile加载程序集,然后找到所需的类型。 Use interface that will be implemented by your concrete classes to avoid having to know the concrete types.
使用将由您的具体类实现的接口,以避免必须了解具体类型。
This thread should help: Finding objects that implement interface from loaded assembly -how to compare types? 该线程应该有所帮助: 从加载的程序集中查找实现接口的对象-如何比较类型?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.