0

我正在尝试在运行时创建动态类,但是当我在最后一行运行程序时出现以下错误。有谁知道如何解决这个问题?我尝试在网上搜索类似的问题,但没有一个解决方案对我有帮助。提前感谢您的帮助

无法加载文件或程序集 'file:///C:\Users\xxxx\AppData\Local\Temp\jelsfwqz.dll' 或其依赖项之一。该系统找不到指定的文件。

string code2 = "using System;" +
"using System.Collections.Generic;" +
"using System.Linq;" +
"using System.Text;" +
"" +

"    public sealed class CustomClass" +
"    {" +

"    }" 
;


        // Compiler and CompilerParameters
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();

        CompilerParameters compParameters = new CompilerParameters();

        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

        // Compile the code
        CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2);

        // Create a new instance of the class 'CustomClass'
        object myClass = res.CompiledAssembly.CreateInstance("CustomClass");
4

1 回答 1

2

固定代码:

    string code2 = 
    "    public sealed class CustomClass" +
    "    {" +

    "    }"
    ;


    // Compiler and CompilerParameters
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();

    CompilerParameters compParameters = new CompilerParameters();

    CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

    **compParameters.ReferencedAssemblies.Add("System.dll");**


    // Compile the code
    CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2);

    // Create a new instance of the class 'CustomClass'
        object myClass = res.CompiledAssembly.CreateInstance("CustomClass");
于 2012-11-16T19:50:12.440 回答