反射和静态方法的奇怪问题

发布于 2024-10-08 01:27:11 字数 999 浏览 4 评论 0原文

Visual Studio 2008 - 框架 3.5 - Visual Basic

您好! 我对反射调用的静态方法有疑问。 在加载我的 win-wpf 时,我在原始目录的同一目录中创建了一个名为“_temp.dll”的“A4Library.dll”副本。 然后,在按钮单击事件中,我以这种方式调用 _temp.dll 上的静态方法:

Dim AssemblyFileName As String = Directory.GetCurrentDirectory() & "\_temp.dll"
Dim oAssembly As Assembly = Assembly.LoadFrom(AssemblyFileName)
Dim TypeName As String = "MyLibrary.MyService"
Dim t As Type = oAssembly.GetType(TypeName)
Dim mi As MethodInfo = t.GetMethod("MyMethod", BindingFlags.Static AndAlso BindingFlags.Public)
Dim bResponse As Boolean = mi.Invoke(Nothing, New Object() {MyPar1, MyPar2})

但只有当 .exe 文件不在 .dll 文件的同一目录中时,这种方法才有效,否则我会得到这个错误(已翻译):

InnerException {“在 [B]MyType 上转换 [A]MyType 是不可能的。类型 A 源自...上下文“Default”中的“F:\MyPath\A4Library.dll”位置。类型 B 源自...在位置“F:\MyPath_temp.dll”的上下文“LoadFrom”中。”}

很奇怪:这似乎与原始 .dll 中的相同方法发生冲突,但我无法理解为什么它看的是原件而不是副本。如果与主程序集相关的 .exe 文件放置在另一个目录中,则一切运行良好。

我需要将 .exe 与 .dll 放在同一文件夹中,如何解决这个问题?

谢谢你! 皮莱吉

Visual Studio 2008 - framework 3.5 - Visual Basic

Hi!
I have a problem with a static method invoked by reflection.
On the loading of my win-wpf I create a copy of "A4Library.dll" with the name "_temp.dll", in the same directory of the original.
Then, on a button-click event, I invoke a static method on the _temp.dll in this way:

Dim AssemblyFileName As String = Directory.GetCurrentDirectory() & "\_temp.dll"
Dim oAssembly As Assembly = Assembly.LoadFrom(AssemblyFileName)
Dim TypeName As String = "MyLibrary.MyService"
Dim t As Type = oAssembly.GetType(TypeName)
Dim mi As MethodInfo = t.GetMethod("MyMethod", BindingFlags.Static AndAlso BindingFlags.Public)
Dim bResponse As Boolean = mi.Invoke(Nothing, New Object() {MyPar1, MyPar2})

But this works well only if I the .exe file is not in the same directory of the .dll files, otherwise I obtain this error (translated):

InnerException {"Cast impossible of [A]MyType on [B]MyType. The type A is originated from ... in the context 'Default' in the position 'F:\MyPath\A4Library.dll'. The type B is originated from ... in the context 'LoadFrom' in the position 'F:\MyPath_temp.dll'."}

It's strange: it seems to be a conflict with the same method in the original .dll, but I can't undertend why it looks at the original and not at the copy. If the .exe file relative to the principal assembly is placed in another directory, all runs well.

I neet to have the .exe in the same folder of the .dll, how can I solve the problem?

Thank you!
Pileggi

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等你爱我 2024-10-15 01:27:11

为什么在执行静态方法之前创建程序集的副本?如果需要创建副本,请将该程序集加载到另一个 AppDomain 中并执行其中的方法。

Why create a copy of assembly before executing static method? If creating a copy is needed, load that assembly in another AppDomain and execute the method in there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文