摘要:Visual Basic一大吸引人的地方是它支持直接的后期绑定。就是说可以直接在代码里访问那些要到运行时才能确定的对象成员。比如这样一段代码:
Dim f As Object = New Form2()f.Show()
Object是没有Show方法的,但是这段代码可以正确运行。这个功能让VB有了很强的灵活性,它能够直接操作没有类型库的COM对象,而C#则很麻烦。在COM时代,VB的后期绑定是通过IDispatch实现的,而.NET时代,它是由Reflection实现的。为了揭开VB后期绑定的秘密,后面几篇就来讨论一下后期绑定的实现原理。
首先,对方法的调用是后期绑定最重要的一个环节,因为实现了后期绑定的方法调用,就能实现对属性的访问和对事件的操作,这基本上就是对象操作的全部内容。VB的编译器在发现后期绑定的调用后,会用Microsoft.VisualBasic.CompilerServices中的相关操作类实现后期绑定的方法调用。其中,LateBinding.InternalLateCall是这个操作的桥梁。我们来看看这个方法的实现。
这段代码是我从IL手工翻译来的,因为流行的反编译器都不能正确反编译VB的When语句。这段代码很可能有错,凑合着看吧:
<DebuggerStepThrough(), _
DebuggerHidden()> _
Friend Function InternalLateCall( _
ByVal o As Object, _
ByVal objType As System.Type, _
ByVal name As String, _
ByVal args() As Object, _
ByVal paramnames() As String, _
ByVal CopyBack() As Boolean, _
ByVal IgnoreReturn As Boolean _
) As Object
'以下变量的名字已经被我安我的理解改变过
Dim binder As Microsoft.VisualBasic.CompilerServices.VBBinder
Dim flags As System.Reflection.BindingFlags
Dim result As Object
Dim correctIReflect As System.Reflection.IReflect
Dim members() As System.Reflection.MemberInfo
Dim argNumber As Integer
Dim firstMember As System.Reflection.MemberInfo
Dim firstMethodBase As System.Reflection.MethodBase
Dim params() As System.Reflection.ParameterInfo
Dim paramsNumber As Integer
Dim paramsInfo As System.Reflection.ParameterInfo
Dim......[
阅读全文]