.Net的Assembly类是否存储变量?
好的,这就是故事。
我有一个程序集数组,它们由 [Assembly].LoadFrom()
启动,加载多个 DLL。初始化时,会调用一个名为 InitMain
的方法(来自 DLL!),该方法在此方法之外设置许多变量,如下所示:
Public Class Example
Dim C As Integer = 0
Public Sub InitMain()
C = 50
End Sub
Public Sub Test()
MsgBox("C = " & C)
End Sub
End Class
如果我在某处使用相同的程序集数组调用方法 Test稍后在主应用程序中(例如按下按钮或其他东西来触发它),它将弹出一个消息框,其中显示:“C = 0”
这是为什么?是否可以在没有任何奇怪的解决方法的情况下修复它?
提前致谢!
Ok so here's the story.
I have an array of Assemblies which are initiated by [Assembly].LoadFrom()
that load a number of DLL's. Upon initialising, a method called InitMain
(from the DLL!) is called, which sets a number of variables outside of this method, like here:
Public Class Example
Dim C As Integer = 0
Public Sub InitMain()
C = 50
End Sub
Public Sub Test()
MsgBox("C = " & C)
End Sub
End Class
If I call the method Test using that same array of Assemblies somewhere later in the main application (like pressing a button or something to trigger it), it will pop up a messagebox with that says: "C = 0"
Why is this? Is it fixable without any odd workarounds?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法 InitMain 和 Test 以及变量 C 都是在调用 Example 中定义的实例变量。 Example 类的每个实例都有自己的方法和变量的副本。
我怀疑您的代码创建了 Example 类的新实例并调用了该实例的 InitMain 方法。稍后您创建一个新实例并对其调用 Test。这两个实例不会共享变量 C 的同一副本。
解决方法是将 C 定义为共享(C# 中的静态)变量。现在,您将只有一份 C 变量的副本,该副本在 Example 类的所有实例之间共享。
您可能还想将 InitMain 和 Test 方法定义为共享。如果这样做,您将只有每个方法的一个实例,并且必须像这样调用它们:Example.InitMain(),而不是创建一个实例并调用该实例的方法。
The methods InitMain and Test, and your variable C are all instance variables defined in your call Example. Each instance of the Example class with have their own copies of both methods and the variable.
I suspect that your code creates a new instance of the Example class and calls the InitMain method on that. Later you create a new instance and call Test on that. These two instances will not share the same copy of the variable C.
The workaround is to define C as a Shared (static in C#) variable. Now you will only have one copy of the C variable that is shared between all instances of the Example class.
You may also want to define the InitMain and Test methods as Shared. If you do so you will only have one instance of each method and must call them like this: Example.InitMain() instead of creating an instance and calling the method on that.
所以你需要在实例化你的类Example之后和调用sub Test之前调用initMain sub?
So you need to call the initMain sub after instantiating your class Example and before calling sub Test?