gpt4 book ai didi

c# - 创建方法信息 : Could not load file or assembly

转载 作者:行者123 更新时间:2023-11-30 12:23:21 24 4
gpt4 key购买 nike

之前在一个循环中,我有一个对 CreateMethodInfo 的工作调用,并且方法签名没有参数。

现在我已经更改了它(出于性能原因)以便所讨论的方法具有参数,并且它现在失败并显示以下错误消息:

Could not load file or assembly 'file:///C:\Users\me\AppData\Local\Temp\qz5wsaeb.dll' or one of its dependencies.

我这样称呼:

var method = CreateMethodInfo(script, "Methods", "GetValue");
method.Invoke(null, new object[] { control });

脚本的值:

public class Methods
{
public static void GetValue(Control control)
{
// During runtime this part is dynamic and can change
control.Location = new System.Drawing.Point(165, 70);
control.Size = new System.Drawing.Size(204, 107);
}
}

我看不出我做错了什么。基本上我想调用该方法并传递一个参数,在本例中是一个控件。

编辑

创建方法信息:

public static MethodInfo CreateMethodInfo(string script, string className, string methodName)
{
using (var compiler = new CSharpCodeProvider())
{
var parms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true,
ReferencedAssemblies = { "System.Drawing.dll","System.Windows.Forms.dll" }
};
return compiler.CompileAssemblyFromSource(parms, script)
.CompiledAssembly.GetType(className)
.GetMethod(methodName);
}
}

最佳答案

将引用的程序集的名称添加到 CompilerParameters 结构中(正如您正确执行的那样)不足以让编译器能够解析对 Control 的引用

public static void GetValue(Control control)

您必须使用 using 语句将引用的程序集名称添加到脚本中,如下所示:

    using System.Drawing;
using System.Windows.Forms;

public class Methods
{
public static void GetValue(Control control)
{
...

或者,如果您愿意,用定义的命名空间限定符号引用:

    public class Methods
{
public static void GetValue(System.Windows.Forms.Control control)
{
...

顺便说一句,您可以通过检查 CompileAssemblyFromSource 返回的对象的 Errors 属性自行解决此类问题。

关于c# - 创建方法信息 : Could not load file or assembly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37308710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com