Using the DefaultMemberAttributeThe DefaultMemberAttribute is applied to a type and takes a string argument indicating the name of the default member. The default member can be invoked by InvokeMember without passing the name of the member to invoke. For example, if we apply the DefaultMemberAttribute to ReflectedClass , naming the HelloWorld method as the default member, we can invoke HelloWorld without naming the method. Listing 4.7 shows the ReflectedClass class and a call to InvokeMember that relies on the DefaultMemberAttribute . Listing 4.7 Applying and Invoking a Default MemberImports System.Reflection <DefaultMember("HelloWorld")> _ Public Class ReflectedClass Private FMessage As String Public Sub New(ByVal Message As String) FMessage = Message End Sub Public Sub New() End Sub Public Shared Sub HelloWorld() MsgBox("HelloWorld") End Sub Public Sub ShowMessage(ByVal Text As String) MsgBox(Text, MsgBoxStyle.Information, "Reflected Method") End Sub End Class 'Excerpt from Form code Private Sub InvokeDefaultMember() Dim HelloWorld As [Assembly] = [Assembly].LoadFrom(Path) Dim ReflectedClass As Type = HelloWorld.GetType("HelloWorld.ReflectedClass") ReflectedClass.InvokeMember("", _ BindingFlags.Public Or _ BindingFlags.Static Or BindingFlags.InvokeMethod, _ Type.DefaultBinder, Nothing, Nothing) End Sub
The DefaultMemberAttribute is applied to the class (as shown in the second line of the listing). The InvokeDefaultMember method at the end of Listing 4.7 demonstrates that we can invoke the default member implicitly by making the first argument to InvokeMember an empty string. The BindingFlags still have to reflect how the member was defined, as demonstrated in the listing. |