gpt4 book ai didi

C# 在内存中编译并创建内存程序集类型的实例

转载 作者:行者123 更新时间:2023-11-30 20:59:32 25 4
gpt4 key购买 nike

如何将程序集加载到内存并使用其名称实例化其类型之一?

我要编译:

    /// <summary>
/// Compiles the input string and saves it in memory
/// </summary>
/// <param name="source"></param>
/// <param name="referencedAssemblies"></param>
/// <returns></returns>
public static CompilerResults LoadScriptsToMemory(string source, List<string> referencedAssemblies)
{
CompilerParameters parameters = new CompilerParameters();

parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = false;

//Add the required assemblies
foreach (string reference in referencedAssemblies)
parameters.ReferencedAssemblies.Add(reference);

foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
if (asm.Location.Contains("Microsoft.Xna") || asm.Location.Contains("Gibbo.Library")
|| asm.Location.Contains("System"))
{
parameters.ReferencedAssemblies.Add(asm.Location);
}
}

return Compile(parameters, source);
}

/// <summary>
/// Compiles a source file with the given parameters and source
/// </summary>
/// <param name="parms"></param>
/// <param name="source"></param>
/// <returns></returns>
private static CompilerResults Compile(CompilerParameters parameters, string source)
{
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
return compiler.CompileAssemblyFromSource(parameters, source);
}

然后,我尝试使用它来实例化上面代码在内存中生成的成员:

    var handler = Activator.CreateInstance(SceneManager.ScriptsAssembly.FullName, name);
ObjectComponent oc = (ObjectComponent)handler.Unwrap();

SceneManager.ScriptsAssembly.FullName :> 我将编译后的程序集保存在 SceneManager.ScriptsAssembly 中。

name :> 我要加载的类型的名称

我遇到了这个错误:

Error loading scene: Could not load file or assembly 'nhvneezw, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

程序集名称正确。可能是什么?

提前致谢。

最佳答案

根据 MSDN ( http://msdn.microsoft.com/en-US/library/system.codedom.compiler.compilerresults.compiledassembly.aspx )

The get accessor for the CompiledAssembly property calls the Load method to load the compiled assembly into the current application domain

您可以使用 Assembly.CreateInstance( http://msdn.microsoft.com/en-US/library/dex1ss7c.aspx ) 方法代替 Activator。如果您只需要通过类型名称创建实例,则必须获取 CompilerResults.CompiledAssembly 属性的值。

关于C# 在内存中编译并创建内存程序集类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15460456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com