简体   繁体   中英

How to pass an object to dynamic code in C#

im using System.CodeDom.Compiler to generate a dynamic code , i need to pass some objects to the functions in code , but when i pass objects they refer to my current name space ...

string code = @"
            using System;
            using " + type + @";
            namespace First
            {
                public class Program
                {
                    static " + type + ".Class1 " + type.ToLower() + " = (" + type + ".Class1)"+o + @";                   
                    public static bool check () {
                        if( " + exp
                        +
                        @")
                            return true;
                        else 
                            return false;
                    }
                    public static void Main()
                    {
                    " +
                       "    Console.WriteLine(\"Hello, world!\");"
                      + @"
                    }
                }
            }
        ";

and i get this error : The name 'MineRuleEngine'(my current name space) does not exist in the current context

my problem is that object "o" is refer to MineRuleEngine.person for example . and my dynamic code doesn't know "MineRuleEngine" namespace

The reason your code doesn't know about this object is because you have to explictly take care of using "external" resources (ie classes)

You have to specify using MyNamespace; in code and you have to add a reference to an assembly containing the namespace.

For example:

 CSharpCodeProvider provider = new CSharpCodeProvider();
 CompilerParameters param = new CompilerParameters(new string[] { "System.dll", "Scripting.dll" });

Also take a look at this question Referencing current assembly with CompilerParameters

i pass the object directly to the method and invoke that by reflection

public static bool check (Object o) {

and put the parameter "o" inside string , and remove static modifier

type + " " + type.ToLower() + " = " + "(" + type + ")o ;"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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