Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
Visual Studio 2010 - Visual Basic
Interfaces (Visual Basic)

Interfaces define the properties, methods, and events that classes can implement. Interfaces allow you to define features as small groups of closely related properties, methods, and events; this reduces compatibility problems because you can develop enhanced implementations for your interfaces without jeopardizing existing code. You can add new features at any time by developing additional interfaces and implementations.

There are several other reasons why you might want to use interfaces instead of class inheritance:

  • Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.

  • Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.

  • Interfaces are better in situations in which you do not have to inherit implementation from a base class.

  • Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

Interface definitions are enclosed within the Interface and End Interface statements. Following the Interface statement, you can add an optional Inherits statement that lists one or more inherited interfaces. The Inherits statements must precede all other statements in the declaration except comments. The remaining statements in the interface definition should be Event, Sub, Function, Property, Interface, Class, Structure, and Enum statements. Interfaces cannot contain any implementation code or statements associated with implementation code, such as End Sub or End Property.

In a namespace, interface statements are Friend by default, but they can also be explicitly declared as Public or Friend. Interfaces defined within classes, modules, interfaces, and structures are Public by default, but they can also be explicitly declared as Public, Friend, Protected, or Private.

NoteNote

The Shadows keyword can be applied to all interface members. The Overloads keyword can be applied to Sub, Function, and Property statements declared in an interface definition. In addition, Property statements can have the Default, ReadOnly, or WriteOnly modifiers. None of the other modifiers—Public, Private, Friend, Protected, Shared, Overrides, MustOverride, or Overridable—are allowed. For more information, see Declaration Contexts and Default Access Levels (Visual Basic).

For example, the following code defines an interface with one function, one property, and one event.

Visual Basic
Interface IAsset
    Event ComittedChange(ByVal Success As Boolean)
    Property Division() As String
    Function GetID() As Integer
End Interface

The Visual Basic reserved word Implements is used in two ways. The Implements statement signifies that a class or structure implements an interface. The Implements keyword signifies that a class member or structure member implements a specific interface member.

Implements Statement

If a class or structure implements one or more interfaces, it must include the Implements statement immediately after the Class or Structure statement. The Implements statement requires a comma-separated list of interfaces to be implemented by a class. The class or structure must implement all interface members using the Implements keyword.

Implements Keyword

The Implements keyword requires a comma-separated list of interface members to be implemented. Generally, only a single interface member is specified, but you can specify multiple members. The specification of an interface member consists of the interface name, which must be specified in an implements statement within the class; a period; and the name of the member function, property, or event to be implemented. The name of a member that implements an interface member can use any legal identifier, and it is not limited to the InterfaceName_MethodName convention used in earlier versions of Visual Basic.

For example, the following code shows how to declare a subroutine named Sub1 that implements a method of an interface:

Visual Basic
Class Class1
    Implements interfaceclass.interface2

    Sub Sub1(ByVal i As Integer) Implements interfaceclass.interface2.Sub1
    End Sub
End Class

The parameter types and return types of the implementing member must match the interface property or member declaration in the interface. The most common way to implement an element of an interface is with a member that has the same name as the interface, as shown in the previous example.

To declare the implementation of an interface method, you can use any attributes that are legal on instance method declarations, including Overloads, Overrides, Overridable, Public, Private, Protected, Friend, Protected Friend, MustOverride, Default, and Static. The Shared attribute is not legal since it defines a class rather than an instance method.

Using Implements, you can also write a single method that implements multiple methods defined in an interface, as in the following example:

Visual Basic
Class Class2
    Implements I1, I2

    Protected Sub M1() Implements I1.M1, I1.M2, I2.M3, I2.M4
    End Sub
End Class

You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.

Interface Implementation Examples

Classes that implement an interface must implement all its properties, methods, and events.

The following example defines two interfaces. The second interface, Interface2, inherits Interface1 and defines an additional property and method.

Visual Basic
Interface Interface1
    Sub sub1(ByVal i As Integer)
End Interface

' Demonstrates interface inheritance.
Interface Interface2
    Inherits Interface1
    Sub M1(ByVal y As Integer)
    ReadOnly Property Num() As Integer
End Interface

The next example implements Interface1, the interface defined in the previous example:

Visual Basic
Public Class ImplementationClass1
    Implements Interface1
    Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
        ' Insert code here to implement this method.
    End Sub
End Class

The final example implements Interface2, including a method inherited from Interface1:

Visual Basic
Public Class ImplementationClass2
    Implements Interface2
    Dim INum As Integer = 0
    Sub sub1(ByVal i As Integer) Implements Interface2.sub1
        ' Insert code here that implements this method.
    End Sub
    Sub M1(ByVal x As Integer) Implements Interface2.M1
        ' Insert code here to implement this method.
    End Sub

    ReadOnly Property Num() As Integer Implements Interface2.Num
        Get
            Num = INum
        End Get
    End Property
End Class

Title

Description

Walkthrough: Creating and Implementing Interfaces (Visual Basic)

Provides a detailed procedure that takes you through the process of defining and implementing your own interface.

Variance in Generic Interfaces (C# and Visual Basic)

Discusses covariance and contravariance in generic interfaces and provides a list of variant generic interfaces in the .NET Framework.

Visual Studio 2010 - Visual Basic
Interfaces (Visual Basic)

Las Interfaces definen las propiedades, métodos y eventos que pueden implementar las clases. Las interfaces le permiten definir características como grupos pequeños de propiedades, métodos y eventos estrechamente relacionados; de esta forma se reducen los problemas de compatibilidad, ya que pueden desarrollarse implementaciones mejoradas para las interfaces sin poner en peligro el código existente. Se pueden agregar nuevas características en cualquier momento, mediante el desarrollo de implementaciones e interfaces adicionales.

Existen otras razones por las que se podría desear utilizar interfaces en lugar de la herencia de clases:

  • Las interfaces admiten mejor las situaciones en las cuales las aplicaciones necesitan el mayor número de tipos de objetos no relacionados posible para proporcionar determinadas funciones.

  • Las interfaces son más flexibles que las clases de base, porque puede definir una única implementación que puede implementar interfaces múltiples.

  • Las interfaces son mejores en situaciones en las que no es necesario heredar una implementación de una clase de base.

  • Las interfaces son útiles cuando no se puede usar la herencia de clases. Por ejemplo, las estructuras no pueden heredarse de las clases, pero pueden implementar interfaces.

Las definiciones de interfaz se encuentran dentro de las instrucciones Interface y End Interface. Después de la instrucción Interface, puede agregar una instrucción Inherits opcional que proporciona una lista de una o varias interfaces heredadas. Las instrucciones Inherits deben ir antes que el resto de instrucciones de una declaración, a excepción de los comentarios. El resto de instrucciones de una definición de interfaz deberían ser instrucciones Event, Sub, Function, Property, Interface, Class, Structure y Enum. Las interfaces no pueden contener código de implementación ni instrucciones asociadas a código de implementación, como End Sub o End Property.

En un espacio de nombres, las instrucciones de interfaz son de manera predeterminada Friend, pero también se pueden declarar explícitamente como Public o Friend. Las interfaces definidas dentro de las clases, módulos, interfaces y estructuras son de manera predeterminada Public, pero también se pueden declarar explícitamente como Public, Friend, Protected o Private.

NotaNota

La palabra clave Shadows se puede aplicar a todos los miembros de la interfaz. La palabra clave Overloads se puede aplicar a las instrucciones declaradas Sub, Function y Property en la definición de una interfaz. Además, las instrucciones Property pueden tener los modificadores Default, ReadOnly o WriteOnly. No se permite ninguno del resto de los modificadores: Public, Private, Friend, Protected, Shared, Overrides, MustOverride o Overridable. Para obtener más información, vea Contextos de declaración y niveles de acceso predeterminados (Visual Basic).

Por ejemplo, en el código siguiente se define una interfaz con una función, una propiedad y un evento.

Visual Basic
Interface IAsset
    Event ComittedChange(ByVal Success As Boolean)
    Property Division() As String
    Function GetID() As Integer
End Interface

La palabra reservada Implements de Visual Basic se usa de dos formas. La instrucción Implements significa que una clase o estructura implementa una interfaz. La palabra clave Implements significa que un miembro de clase o de estructura implementa un miembro de interfaz específico.

Implements (Instrucción)

Si una clase o estructura implementa una o más interfaces, debe incluir la instrucción Implements inmediatamente después de la instrucción Class o Structure. La instrucción Implements exige que una lista separada por comas de interfaces sea implementada por una clase. La clase o estructura debe implementar todos los miembros de interfaz mediante la palabra clave Implements.

La palabra clave Implements

La palabra clave Implements requiere una lista separada por comas de los miembros de la interfaz que deben implementarse. Por lo general, se especifica solamente un único miembro de interfaz, pero se pueden especificar varios miembros. La especificación de un miembro de interfaz consta del nombre de la interfaz, que debe especificarse en una instrucción Implements dentro de la clase, un punto y el nombre del evento, propiedad o función miembro que debe implementarse. El nombre de un miembro que implementa un miembro de interfaz puede utilizar cualquier identificador permitido y no se limita a la convención InterfaceName_MethodName que se utilizaba en las versiones anteriores de Visual Basic.

Por ejemplo, el código siguiente muestra cómo declarar una subrutina denominada Sub1 que implementa un método de una interfaz:

Visual Basic
Class Class1
    Implements interfaceclass.interface2

    Sub Sub1(ByVal i As Integer) Implements interfaceclass.interface2.Sub1
    End Sub
End Class

Los tipos de parámetro y de valores devueltos del miembro que realiza la implementación deben coincidir con la propiedad de interfaz o la declaración de miembro de la interfaz. La forma más habitual de implementar un elemento de una interfaz es con un miembro que tenga el mismo nombre que la interfaz, como se muestra en el ejemplo anterior.

Para declarar la implementación de un método de interfaz, puede utilizar cualquier atributo permitido en las declaraciones de método de instancia, incluidos Overloads, Overrides, Overridable, Public, Private, Protected, Friend, Protected Friend, MustOverride, Default y Static. El atributo Shared no está permitido, ya que define una clase en lugar de un método de instancia.

Con Implements también puede crear un único método que implemente varios métodos definidos en una interfaz, como en el ejemplo siguiente:

Visual Basic
Class Class2
    Implements I1, I2

    Protected Sub M1() Implements I1.M1, I1.M2, I2.M3, I2.M4
    End Sub
End Class

Puede utilizar un miembro privado para implementar un miembro de interfaz. Cuando un miembro privado implementa un miembro de una interfaz, el miembro pasa a estar disponible por medio de la interfaz, aunque no está disponible directamente en las variables de objeto para la clase.

Ejemplos de implementación de interfaces

Las clases que implementan una interfaz deben implementar todas sus propiedades, métodos y eventos.

El ejemplo siguiente define dos interfaces. La segunda interfaz, Interface2, hereda Interface1 y define un método y una propiedad adicional.

Visual Basic
Interface Interface1
    Sub sub1(ByVal i As Integer)
End Interface

' Demonstrates interface inheritance.
Interface Interface2
    Inherits Interface1
    Sub M1(ByVal y As Integer)
    ReadOnly Property Num() As Integer
End Interface

El ejemplo siguiente implementa Interface1, la interfaz definida en el ejemplo anterior:

Visual Basic
Public Class ImplementationClass1
    Implements Interface1
    Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
        ' Insert code here to implement this method.
    End Sub
End Class

El ejemplo final implementa Interface2, incluyendo un método heredado de Interface1:

Visual Basic
Public Class ImplementationClass2
    Implements Interface2
    Dim INum As Integer = 0
    Sub sub1(ByVal i As Integer) Implements Interface2.sub1
        ' Insert code here that implements this method.
    End Sub
    Sub M1(ByVal x As Integer) Implements Interface2.M1
        ' Insert code here to implement this method.
    End Sub

    ReadOnly Property Num() As Integer Implements Interface2.Num
        Get
            Num = INum
        End Get
    End Property
End Class

Título

Descripción

Tutorial: Crear e implementar interfaces (Visual Basic)

Proporciona un procedimiento detallado que le conduce a través del proceso de definición e implementación de su propia interfaz.

Varianza en interfaces genéricas (C# y Visual Basic)

Se describe la covarianza y la contravarianza en las interfaces genéricas y se proporciona una lista de interfaces genéricas variantes en .NET Framework.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker