简体   繁体   English

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

[英]passing class types to runtime compiled code C#

I am trying to read and compile an external file (it's in a string constant for now) 我正在尝试读取和编译外部文件(目前位于字符串常量中)

I can use basic primitives in the external code but I can't seem to figure out how to pass it a class type without it getting angry -heres what I have (excluding the using lines) 我可以在外部代码中使用基本原语,但似乎无法弄清楚如何在不生气的情况下将其传递给类类型-这就是我所拥有的(不包括使用行)

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

Help would be appreciated 帮助将不胜感激

When I looked at your code it appears the problem is that your 'new' assembly (the string version) does not know about the currently executing assembly (same namespace or not). 当我查看您的代码时,似乎出现的问题是您的“新”程序集(字符串版本)不知道当前正在执行的程序集(名称空间是否相同)。 The solution is to reference the currently executing assembly. 解决方案是引用当前正在执行的程序集。 Add this line right after your compilerParams initialization: 在您的compilerParams初始化之后立即添加以下行:

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

Also, when I fired up your code I changed the myClass declaration to public. 另外,当我启动您的代码时,我将myClass声明更改为public。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM