Compartir a través de


Clase ComImportAttribute

 

Publicado: octubre de 2016

Indica que el tipo con atributos estaba previamente definido en COM.

Espacio de nombres:   System.Runtime.InteropServices
Ensamblado:  mscorlib (en mscorlib.dll)

Jerarquía de herencia

System.Object
  System.Attribute
    System.Runtime.InteropServices.ComImportAttribute

Sintaxis

[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Interface, 
    Inherited = false)]
[ComVisibleAttribute(true)]
public sealed class ComImportAttribute : Attribute
[AttributeUsageAttribute(AttributeTargets::Class | AttributeTargets::Interface, 
    Inherited = false)]
[ComVisibleAttribute(true)]
public ref class ComImportAttribute sealed : Attribute
[<Sealed>]
[<AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Interface,
    Inherited = false)>]
[<ComVisibleAttribute(true)>]
type ComImportAttribute = 
    class
        inherit Attribute
    end
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Interface,
    Inherited := False)>
<ComVisibleAttribute(True)>
Public NotInheritable Class ComImportAttribute
    Inherits Attribute

Constructores

Nombre Descripción
System_CAPS_pubmethod ComImportAttribute()

Inicializa una nueva instancia de ComImportAttribute.

Propiedades

Nombre Descripción
System_CAPS_pubproperty TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.(Heredado de Attribute).

Métodos

Nombre Descripción
System_CAPS_pubmethod Equals(Object)

Esta API admite la infraestructura producto y no está diseñada para usarse directamente desde el código. Devuelve un valor que indica si esta instancia es igual que un objeto especificado.(Heredado de Attribute).

System_CAPS_pubmethod GetHashCode()

Devuelve el código hash de esta instancia.(Heredado de Attribute).

System_CAPS_pubmethod GetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethod IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.(Heredado de Attribute).

System_CAPS_pubmethod Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.(Heredado de Attribute).

System_CAPS_pubmethod ToString()

Devuelve una cadena que representa el objeto actual.(Heredado de Object).

Implementaciones de interfaz explícitas

Nombre Descripción
System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.(Heredado de Attribute).

Comentarios

You can apply this attribute to classes or interfaces, although the [<topic://cpgrfTypeLibraryImporterTlbimpexe>] typically applies it for you when it imports a type library.

ComImportAttribute is a pseudo-custom attribute that indicates that a type has been defined in a previously published type library. The common language runtime treats these types differently when activating, exporting, coercing, and so on.

Nota

All base COM types that are inherited by a managed object must aggregate the Free Threaded Marshaller (FTM). COM types that do not aggregate the FTM can't be inherited by managed objects.

Ejemplos

The following example demonstrates how to apply the T:System.Runtime.InteropServices.ComImportAttribute to a managed interface declaration. You apply this attribute only when generating an interop assembly manually in source code, and want to simulate the metadata produced by Tlbimp.exe.

using System;
using System.Runtime.InteropServices;

namespace MyModule
{
    // If you do not have a type library for an interface
    // you can redeclare it using ComImportAttribute.

    // This is how the interface would look in an idl file.

    //[
    //object,
    //uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"),
    //dual, helpstring("IMyStorage Interface"),
    //pointer_default(unique)
    //]
    //interface IMyStorage : IDispatch
    //{
    //  [id(1)]
    //  HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem);
    //  [id(2)]
    //  HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems);
    //  [id(3)]
    //  HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems);
    //  [id(4), propget]
    //  HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty);
    //};

    // This is the managed declaration.

    [ComImport]
    [Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")]
    public interface IMyStorage  
    {
        [DispId(1)]
        [return : MarshalAs( UnmanagedType.Interface )]
        Object GetItem( [In, MarshalAs( UnmanagedType.BStr )] String bstrName );

        [DispId(2)]
        void GetItems( [In, MarshalAs( UnmanagedType.BStr )] String bstrLocation, 
            [Out, MarshalAs( UnmanagedType.SafeArray, 
                      SafeArraySubType = VarEnum.VT_VARIANT )] out Object[] Items );


        [DispId(3)]
        void GetItemDescriptions( [In] String bstrLocation, 
            [In, Out, MarshalAs( UnmanagedType.SafeArray )] ref Object[] varDescriptions );

        bool IsEmpty 
        {
            [DispId(4)]
            [return : MarshalAs( UnmanagedType.VariantBool )]
            get;
        }
    }
}
Imports System
Imports System.Runtime.InteropServices

Module MyModule
    ' If you do not have a type library for an interface
    ' you can redeclare it using ComImportAttribute.

    ' This is how the interface would look in an idl file.

    '[
    'object,
    'uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"),
    'dual,  helpstring("IMyStorage Interface"),
    'pointer_default(unique)
    ']
    'interface IMyStorage : IDispatch
    '{
    '   [id(1)]
    '   HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem);
    '   [id(2)]
    '   HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems);
    '   [id(3)]
    '   HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems);
    '   [id(4), propget]
    '   HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty);
    '};

    ' This is the managed declaration.

    <ComImport(), Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")> _
    Public Interface IMyStorage
        <DispId(1)> _
        Function GetItem(<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByVal bstrName As String) _
           As <MarshalAs(UnmanagedType.Interface)> Object

        <DispId(2)> _
        Function GetItems(<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByVal bstrLocation As String, _
           <OutAttribute(), MarshalAs(UnmanagedType.SafeArray, SafeArraySubType := VarEnum.VT_VARIANT)> _
                                      ByVal Items() As Object)

        <DispId(3)> _
        Function GetItemDescriptions(<InAttribute()> ByVal bstrLocation As String, _
           <InAttribute(), OutAttribute(), _
                      MarshalAs(UnmanagedType.SafeArray)> ByRef varDescriptions() As Object)

        <DispId(4)> _
        ReadOnly Property IsEmpty(<MarshalAs(UnmanagedType.VariantBool)> ByVal bEmpty As Boolean)

    End Interface
End Module
using namespace System;
using namespace System::Runtime::InteropServices;

// If you do not have a type library for an interface
// you can redeclare it using ComImportAttribute.
// This is how the interface would look in an idl file.
//[
//object,
//uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"),
//dual, helpstring("IMyStorage Interface"),
//pointer_default(unique)
//]
//interface IMyStorage : IDispatch
//{
// [id(1)]
// HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem);
// [id(2)]
// HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems);
// [id(3)]
// HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems);
// [id(4), propget]
// HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty);
//};
// This is the managed declaration.

[ComImport]
[Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")]
interface class IMyStorage
{
   [DispId(1)]
   Object^ GetItem( [In,MarshalAs(UnmanagedType::BStr)]String^ bstrName );

   //[return : MarshalAs(UnmanagedType::Interface)]

   [DispId(2)]
   void GetItems( [In,MarshalAs(UnmanagedType::BStr)]String^ bstrLocation, [Out,MarshalAs(UnmanagedType::SafeArray,
   SafeArraySubType=VarEnum::VT_VARIANT)]array<Object^>^Items );

   [DispId(3)]
   void GetItemDescriptions( [In]String^ bstrLocation, [In,Out,MarshalAs(UnmanagedType::SafeArray)]array<Object^>^varDescriptions );

   property bool IsEmpty 
   {
      [DispId(4)]
      [returnvalue:MarshalAs(UnmanagedType::VariantBool)]
      bool get();
   }
};

Información de versión

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

Seguridad para subprocesos

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Ver también

Espacio de nombres System.Runtime.InteropServices
Tlbimp.exe (Type Library Importer)

Volver al principio