来自图书馆的反思 [英] Reflection from Library dll
问题描述
我想使用反射来显示调用程序集中设置的全局值。
在调用程序集中我有一个主模块指定全程使用的许多全局变量。我还希望能够在库dll中使用它们。
程序集的根命名空间是ERP_Generic。主模块的名称是Main。
主要模块:(显然所有这些都是为了说明目的非常简化)
I want to use reflection to reveal the values of global from that are set in the calling assembly.
In the calling assembly I have a main module that specifies many global variables used throughout. I also want to be able to use these in the library dll.
The root namespace of the assembly is "ERP_Generic". The name of the main module is "Main".
The main module: (obviously all this is very simplified for illustration purposes)
Module Main
Public MNApplDir As String = "C:\Program\MyAppDir"
End Module
在库dll中,我有一个测试子:
In the library dll, I have a test sub:
Public Sub Test1()
Dim mParentAssy As Assembly = Assembly.GetEntryAssembly ' the assembly that called this library class
Dim moduleType As Type = mParentAssy.GetType("ERP_Generic.Main")
Dim myFields As FieldInfo() = moduleType.GetFields((BindingFlags.Public Or BindingFlags.Instance))
Dim mFldName As String = myFields(0).Name
Dim istr As String = myFields(0).GetValue(mParentAssy)
End Sub
当调用此子程序并逐步执行它时,myFields数组没有任何成员。
我不知道为什么module.GetFields找不到字段。
When this sub is called and I step through it, the myFields array does not have any members.
I don't know why the module.GetFields can't find the fields.
推荐答案
我已经弄明白了。 FieldInfo行已更改为:
Dim myFields As FieldInfo()= moduleType.GetFields()
我添加了一个循环来查找我正在寻找的变量:
I have figured it out. The FieldInfo line has been changed to:
Dim myFields As FieldInfo() = moduleType.GetFields()
And I have added a loop to find the variables I am seeking:
For i As Short = 0 To myFields.Length - 1 Step 1
If myFields(i).Name = "MNApplDir" Then
MNApplDir = myFields(i).GetValue(mParentAssy)
End If
Next i
这是正常的。
This works correctly.
这篇关于来自图书馆的反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!