1

我正在尝试读取和编译一个外部文件(它现在在一个字符串常量中)

我可以在外部代码中使用基本原语,但我似乎无法弄清楚如何在不生气的情况下将其传递给类类型 - 这就是我所拥有的(不包括使用行)

class myClass
{
    public int x;
    public myClass(int n)
    {
        x = n;
    }
}
class Program
{
    static void Main(string[] args)
    {
        string source =
        @"
           namespace ConsoleApplication1
           {
               public class Bar
               {
                   public int getNumber(myClass c)
                   {
                       return c.x;
                   }
              }
          }";     
            Dictionary<string, string> providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v3.5"}
            };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
            CompilerParameters compilerParams = new CompilerParameters
            {
                GenerateInMemory = true,
                GenerateExecutable = false
            };
            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
            if (results.Errors.Count != 0)
                throw new Exception("Failed");
        object o = results.CompiledAssembly.CreateInstance("ConsoleApplication1.Bar");
        MethodInfo mi = o.GetType().GetMethod("getNumber");
        object[] param = new object[1];
        myClass c = new myClass(5);
        param[0] = c;
        int myInt = (int)mi.Invoke(o, param);
        Console.Write(myInt);
        Console.ReadLine();
    }
}

帮助将不胜感激

4

1 回答 1

0

当我查看您的代码时,问题似乎是您的“新”程序集(字符串版本)不知道当前正在执行的程序集(是否相同的命名空间)。解决方案是引用当前正在执行的程序集。在你的 compilerParams 初始化之后添加这一行:

compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

此外,当我启动您的代码时,我将 myClass 声明更改为 public。

于 2013-12-03T04:18:42.427 回答