Visual Studio 2010 - Visual Basic Partial Methods (Visual Basic) Partial methods enable developers to insert custom logic into code. Typically, the code is part of a designer-generated class. Partial methods are defined in a partial class that is created by a code generator, and they are commonly used to provide notification that something has been changed. They enable the developer to specify custom behavior in response to the change. The designer of the code generator defines only the method signature and one or more calls to the method. Developers can then provide implementations for the method if they want to customize the behavior of the generated code. When no implementation is provided, calls to the method are removed by the compiler, resulting in no additional performance overhead.

Declaration
The generated code marks the definition of a partial method by placing the keyword Partial at the start of the signature line.
Partial Private Sub QuantityChanged()
End Sub
The definition must meet the following conditions: The method must be a Sub, not a Function. The body of the method must be left empty. The access modifier must be Private.

Implementation
The implementation consists primarily of filling in the body of the partial method. The implementation is typically in a separate partial class from the definition, and is written by a developer who wants to extend the generated code.
Private Sub QuantityChanged()
' Code for executing the desired action.
End Sub
The previous example duplicates the signature in the declaration exactly, but variations are possible. In particular, other modifiers can be added, such as Overloads or Overrides. Only one Overrides modifier is permitted. For more information about method modifiers, see Sub Statement (Visual Basic).

Use
You call a partial method as you would call any other Sub procedure. If the method has been implemented, the arguments are evaluated and the body of the method is executed. However, remember that implementing a partial method is optional. If the method is not implemented, a call to it has no effect, and expressions passed as arguments to the method are not evaluated.

Example
In a file named Product.Designer.vb, define a Product class that has a Quantity property.
Partial Class Product
Private _Quantity As Integer
Property Quantity() As Integer
Get
Return _Quantity
End Get
Set(ByVal value As Integer)
_Quantity = value
QuantityChanged()
End Set
End Property
' Provide a signature for the partial method.
Partial Private Sub QuantityChanged()
End Sub
End Class
In a file named Product.vb, provide an implementation for QuantityChanged.
Partial Class Product
Private Sub QuantityChanged()
MsgBox("Quantity was changed to " & Me.Quantity)
End Sub
End Class
Finally, in the Main method of a project, declare a Product instance and provide an initial value for its Quantity property.
Module Module1
Sub Main()
Dim product1 As New Product With {.Quantity = 100}
End Sub
End Module
A message box should appear that displays this message: Quantity was changed to 100

See Also
|
Visual Studio 2010 - Visual Basic Métodos parciales (Visual Basic) Los métodos parciales permiten a los programadores insertar la lógica personalizada en el código. Normalmente, el código forma parte de una clase generada por el diseñador. Los métodos parciales se definen en una clase parcial que crea un generador de código y se suelen usar para notificar que se ha cambiado algo. Permiten al programador especificar el comportamiento personalizado en respuesta al cambio. El diseñador del generador de código define sólo la firma de método y una o más llamadas al mismo. Después, los programadores pueden proporcionar las implementaciones del método si desean personalizar el comportamiento del código generado. Cuando no se proporciona ninguna implementación, el compilador quita las llamadas al método produciéndose una sobrecarga de rendimiento adicional.

Declaración
El código generado marca la definición de un método parcial colocando la palabra clave Partial al principio de la línea de firma.
Partial Private Sub QuantityChanged()
End Sub
La definición debe cumplir las condiciones siguientes: El método debe ser Sub, no Function. El cuerpo del método debe quedar vacío. El modificador de acceso debe ser Private.

Implementación
La implementación está formada principalmente por el rellenado del cuerpo del método parcial. Normalmente, la implementación está en una clase parcial independiente de la definición y la escribe un programador que desea extender el código generado.
Private Sub QuantityChanged()
' Code for executing the desired action.
End Sub
El ejemplo anterior duplica la firma en la declaración exactamente, pero son posibles las variaciones. En particular, se pueden agregar otros modificadores, como Overloads u Overrides. Se permite sólo un modificador Overrides. Para obtener más información sobre modificadores de métodos, vea Sub (Instrucción, Visual Basic).

Utilice
Llame a un método parcial como llamaría a cualquier otro procedimiento Sub. Si se ha implementado el método, se evalúan los argumentos y se ejecuta el cuerpo del método. Sin embargo, recuerde que implementar un método parcial es opcional. Si no se implementa el método, una llamada a éste no tiene ningún efecto y no se evalúan las expresiones pasadas como argumentos al método.

Ejemplo
En un archivo denominado Product.Designer.vb, defina una clase Product que tiene una propiedad Quantity.
Partial Class Product
Private _Quantity As Integer
Property Quantity() As Integer
Get
Return _Quantity
End Get
Set(ByVal value As Integer)
_Quantity = value
QuantityChanged()
End Set
End Property
' Provide a signature for the partial method.
Partial Private Sub QuantityChanged()
End Sub
End Class
En un archivo denominado Product.vb, proporcione una implementación para QuantityChanged.
Partial Class Product
Private Sub QuantityChanged()
MsgBox("Quantity was changed to " & Me.Quantity)
End Sub
End Class
Finalmente, en el método Main de un proyecto, declare una instancia de Product y proporcione un valor inicial para su propiedad Quantity.
Module Module1
Sub Main()
Dim product1 As New Product With {.Quantity = 100}
End Sub
End Module
Debe aparecer un cuadro de mensaje con este mensaje: Quantity was changed to 100

Vea también
|