我正在尝试读取和编译一个外部文件(它现在在一个字符串常量中)
我可以在外部代码中使用基本原语,但我似乎无法弄清楚如何在不生气的情况下将其传递给类类型 - 这就是我所拥有的(不包括使用行)
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();
}
}
帮助将不胜感激