将类类型传递给运行时编译的代码C#

时间:2013-12-03 02:48:34

标签: c# runtime-compilation

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

我可以在外部代码中使用基本原语但我似乎无法弄清楚如何将它传递给类类型而不会生气 - 我拥有的东西(不包括使用线)

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();
    }
}

帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

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

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

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