| [ Team LiB ] |
|
Recipe 17.2 Call a .NET Component Containing a Parameterized Constructor17.2.1 ProblemAttempting to call a .NET class containing a parameterized constructor generates the compile error "Invalid use of New keyword". Is there some sort of workaround so that I can call a .NET class containing a parameterized constructor? 17.2.2 SolutionTo see the problem, you will need to follow these steps:
Figure 17-3. This compile error is triggered when you attempt to instantiate a .NET class containing a parameterized constructor![]()
The Circle class is shown here: Public Class Circle
' NOTE: This class contains a
' parameterized constructor which
' prevents it from being called
' by a COM program.
Private RadiusVal As Double
Public Sub New(ByVal Radius As Double)
' This constructor takes a parameter
RadiusVal = Radius
End Sub
Public Property Radius( ) As Double
Get
Return RadiusVal
End Get
Set(ByVal Value As Double)
RadiusVal = Value
End Set
End Property
Public Function Area( ) As Double
Return Radius ^ 2 * System.Math.PI
End Function
Public Function Circumference( ) As Double
Return 2 * Radius * System.Math.PI
End Function
End Class
This class is inaccessible from Access because its constructor (the New subroutine) contains a parameter. The trick to being able to call the inaccessible class from Access is to create a helper class that you can use to call the unavailable class. To create a helper class that you can use to call the Circle class, follow these steps:
Figure 17-4. frmCircleUsingHelper instantiates a helper class, CircleCOM, which calls the inaccessible class, Circle![]() 17.2.3 DiscussionThe helper class could have been constructed in a number of ways. Although we chose to use a derived class, the helper class could also have been independent of the original class. The helper class could live within the same component or in a separate component. In this example, we chose to make the helper class a derived class that lives in the same component as the inaccessible class. In this example, you were able to use the CircleCOM class to call the Circle class. In instantiating the Circle class, CircleCOM passed a dummy radius value to the constructor. Because Circle also included a Radius property, you were able to specify the radius value prior to calling the Area method. There may be some classes where properties that duplicate the constructor parameters are not available. In these cases, it may be difficult if not impossible to create a helper class that is able to instantiate the inaccessible class for you. Many of the built-in classes of the .NET Framework contain parameterized constructors. This means that you will need to create a lot of helper classes in order to work with these classes. |
| [ Team LiB ] |
|