Using the DefaultMemberAttribute

Using the DefaultMemberAttribute

The 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 Member
 Imports 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 


Listing 4.7 is not a complete listing. To test the code in Listing 4.7, run the LoadAssembly.sln and call the InvokeDefaultMember method.

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.

Visual Basic. NET Power Coding
Visual Basic(R) .NET Power Coding
ISBN: 0672324075
EAN: 2147483647
Year: 2005
Pages: 215
Authors: Paul Kimmel © 2008-2017.
If you may any questions please contact us: