日期:2014-05-18  浏览次数:20924 次

把字符串反射成可执行代码中,怎样在Invoke中传一个DataSet或DataTable?
double calculated = Convert.ToDouble(result.CompiledAssembly.GetType("demo.calculation").GetMethod("dowork").Invoke(null, new object[] { ds }));
怎样给dowork这个方法传一个DataSet?

//反射出来的一个类
static string GenerateCodeBlocks()
  {
  string code =
  "using System;" +
  "namespace demo" +
  "{" +
  "public static class calculation" +
  "{" +
  "public static double dowork(DataSet ds)" +
  "{ return \"Hello\";}}}"; 
  return code;
  }

------解决方案--------------------
CompilerParameters loParameters = new CompilerParameters();

loParameters.GenerateInMemory = true;
//loParameters.OutputAssembly = "xxx.dll";
//loParameters.ReferencedAssemblies.Add("mscorlib.dll");
loParameters.ReferencedAssemblies.Add("System.dll");
loParameters.ReferencedAssemblies.Add("System.Data.dll");
loParameters.ReferencedAssemblies.Add("System.XML.dll");

CompilerResults result = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(loParameters, GenerateCodeBlocks());
if (result.Errors.HasErrors)
{
foreach (CompilerError error in result.Errors)
{
Console.WriteLine(error.ErrorText);
}

}
else
{
DataSet ds = new DataSet();
Assembly assembly = result.CompiledAssembly;
double calculated = Convert.ToDouble(assembly.GetType("demo.calculation").GetMethod("dowork").Invoke(null, new object[] { ds }));
Console.WriteLine(calculated);
}



static string GenerateCodeBlocks()
{
string code =
"using System;using System.Data;" +
"namespace demo" +
"{" +
"public static class calculation" +
"{" +
"public static double dowork(DataSet ds)" +
"{ return 1;}}}";
return code;
}
------解决方案--------------------
探讨

真接传一个DataSet,编译通过,但执行出错呀。如果传方法参数为public static double dowork(int num)
,
这样调用就可以呀,就是不能用DataSet!
int num=2;
.Invoke(null, new object[] { num }));