反射中关于程序集引用的问题。
public static object dddd()
{
// EngineBase.fRegion(g, EngineBase.intersect(EngineBase.addEllipse(50, 50, 50, 50), EngineBase.addEllipse(60, 60, 50, 50))); string className = "EngineBase";
string methodName = "getResult";
string expression = "double a = 2.0; int b = 3;return Math.Sqrt(a+b);";
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
Format("using System;using System.Reflection;using System.Drawing;sealed class {0}{{public static double {1}(){{{2}}}}}",
className, methodName, expression));
if (cr.Errors.Count > 0)
{
string msg = "Expression(\"" + null + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
object instance = cr.CompiledAssembly.CreateInstance(className);
MethodInfo methodinfo = instance.GetType().GetMethod(methodName);
//如果是静态方法就执行(非静态我没试过)
if (methodinfo != null)
{
if (methodinfo.IsStatic)
{
//调用函数
return methodinfo.Invoke(null, null);
}
}
return 0;
}
在执行p.GenerateInMemory = true;
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
Format("using System;using System.Drawing;sealed class {0}{{public static System.Drawing.Drawing2D.GraphicsPath {1}(){{{2}}}}}",
className, methodName, expression));的时候为什么说我命名空间“System”中不存在类型或命名空间名称“Drawing”(是缺少程序集引用吗?);如果我把using System.Drawing去掉就对了。虽然这个例子是用不到using System.Drawing。但是我会用到这样的情况,请问这是为什么?
{
string className = "EngineBase";//是另一个类EngineBase,里面有addEllipse函数,
string methodName = "getResult";
string expression = "EngineBase.addEllipse(50, 50, 50, 50);";
CompilerParameters p = new CompilerParameters(new string[] { "System.Drawing.dll"}); p.GenerateInMemory = true;
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
Format("using System;sealed class {0}{{public static System.Drawing.Drawing2D.GraphicsPath {1}(){{{2}}}}}",
className, methodName, expression));
if (cr.Errors.Count > 0)
{ string msg = "EngineBase(\"" + null + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
object instance = cr.CompiledAssembly.CreateInstance(className);
MethodInfo methodinfo = instance.GetType().GetMethod(methodName);
//如果是静态方法就执行(非静态我没试过)
if (methodinfo != null)
{
if (methodinfo.IsStatic)
{
//调用函数
return methodinfo.Invoke(null, null);
}
}
return 0;
}
可是在执行的时候,说EngineBase”并不包含“addEllipse”的定义,请问为什么
CompilerParameters p = new CompilerParameters(new string[] { "System.Drawing.dll", "EngineBase.dll" });